NSDateFormatter return wrong date + Swift

Sanjay Kumar picture Sanjay Kumar · Apr 2, 2015 · Viewed 21.2k times · Source

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

Answer

Christos Chadjikyriacou picture Christos Chadjikyriacou · Apr 2, 2015

I had the same problem and i this worked for me

You need to set the time zone

formatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00")