Search code examples
iosswiftdatetimensdateformatter

String to NSdate returns nil


I want to separate my String dateTime to different variables date and time because I will display it separately. How could I do this?

Here's my code in getting the date only and it returns nil:

let datetime = "2015-04-06T13:24:11.913"
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM-DD-YYYY"
    let date = dateFormatter.dateFromString(datetime)
    println(date)

Thanks in advance.

Update: This is my error, enter image description here

Update 2: It doesn't return an error but it gives me the wrong Month for the formatted date

enter image description here


Solution

  • Besides the problem that the string you were testing had milliseconds while the date from your array has only seconds, now the problem is that Y is for week of year. You need to use lowercase "y" with the date format and also lowercase "d". The date format should look like this:

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    

    to extract the month component from a date you can use this extension:

    extension Date {
        var month: Int {
            Calendar(identifier: .gregorian).component(.month, from: self)
        }
    }
    
    
    NSDate().month   // 5