Search code examples
swiftnsdatensdateformatterstring-to-datetime

NSDateFormatter return wrong date + Swift


Code :

let dateString = "2016-04-02"
    var formatter: NSDateFormatter = NSDateFormatter()
    formatter.timeZone = NSTimeZone(abbreviation: "GMT +3:00")
    formatter.dateFormat = "yyyy-MM-dd"
    println("dateString: \(dateString)")
    formatter.locale =  NSLocale(localeIdentifier: "en_US_POSIX")
    let date = formatter.dateFromString(dateString)
    println("date: \(date)")

    formatter.dateFormat = "yyyy-MM-dd"
    let formattedDateString = formatter.stringFromDate(date!)
    println("formattedDateString: \(formattedDateString)")

Output :

dateString: 2016-04-02
date: Optional(2016-04-01 21:00:00 +0000)
formattedDateString: 2016-04-02
2016-04-01 21:00:00 +0000

I am trying to convert a string to NSDate datatype but not getting correct value. I have tried many solutions but its not returning correct value. I need it in yyyy-MM-dd format (2016-04-02) same as my input "2016-04-02". If someone can help would be really apriciated. Thanks in advance


Solution

  • When you convert from string to NSDate, if you do not set the timezone to the formatter, you will get the NSDate of a date in your local time zone. I suppose that your time zone is GMT+3 .

    Then, when you show the value of 'date' (using println, NSLog but not NSDateFormatter), without setting the time zone, you will get GMT+0 time. That why you got 3h later.

    Depend on how to use NSDateFormatter, you will have the date string as you want. In your case, It returns what you want, doesn't it?

    Remember that NSDate presents a moment of time.

    let dateString = "2016-04-02"
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    println("dateString: \(dateString)")
    
    formatter.locale =  NSLocale(localeIdentifier: "en_US_POSIX")
    let date = formatter.dateFromString(dateString) //without specify timezone, your dateString "2016-04-02" is your local time (GMT-3),  
    //means it's 2016-04-02 00:00:000 at GMT+0. That is the value that NSDate holds.
    
    println("date: \(date)") //that why it show 2016-04-01 21:00:000, but not 2016-04-02 00:00:000
    
    formatter.dateFormat = "yyyy-MM-dd"
    let formattedDateString = formatter.stringFromDate(date!)
    println("formattedDateString: \(formattedDateString)")