Apple Ramos
Apple Ramos

Reputation: 275

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

Upvotes: 0

Views: 2260

Answers (5)

Leo Dabus
Leo Dabus

Reputation: 236360

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

Upvotes: 1

Yuyutsu
Yuyutsu

Reputation: 2527

        let datetime = "2015-04-06T13:24:11" //"2015-04-06T13:24:11.913"
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-mm-dd'T'HH:mm:ss" //"yyyy-mm-dd'T'HH:mm:ss.SSS"
        let date = dateFormatter.dateFromString(datetime)
        let myTime = NSDateFormatter.localizedStringFromDate(date!, dateStyle: .NoStyle , timeStyle: .MediumStyle)
        let myDate = NSDateFormatter.localizedStringFromDate(date!, dateStyle: .ShortStyle , timeStyle: .NoStyle)

        println(date!)//DateWithTime
        println(myDate)//Date
        println(myTime)//time 

This helps you for formatting.. NSDateFormatter_Class enter image description here Thanks to @LeonardoSavioDabus for given this image => Swift NSDate UTC time and local time

Upvotes: 3

John Estropia
John Estropia

Reputation: 17500

All of the NSDateFormatters in other answers will give the wrong date once the user sets the iOS calendar to anything other than the gregorian calendar. Your date string doesn't mention any timezone as well so I'm going to assume is UTC.

let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(name: "UTC")
formatter.calendar = NSCalendar.gregorianCalendar()
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS"

Upvotes: 0

Leo
Leo

Reputation: 24714

Use this formatter

let datetime = "2015-04-06T13:24:11.913"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.dateFromString(datetime)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour, fromDate: date!)
components.day//This is 6

Your formatter have to match your string

This is my playground screenshot,it works well. enter image description here

Upvotes: 5

Viral Savaj
Viral Savaj

Reputation: 3389

Try like this way,

    let datetime = "2015-04-06T13:24:11.913"
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    let dateFromString = dateFormatter.dateFromString(datetime)
    var calendar = NSCalendar.currentCalendar()
    var components:NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond | NSCalendarUnit.CalendarUnitHour, fromDate: dateFromString!)
    var stringDate = "\(components.month)-\(components.day)-\(components.year)"
    var stringTime = "\(components.hour):\(components.minute):\(components.second)"
    println(stringDate)
    println(stringTime)

You will get output Like :

4-6-2015

13:24:11

Enjoy Coding !!

Upvotes: -1

Related Questions