Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 802
Sanjay Kumar Avatar asked Apr 02 '15 07:04

Sanjay Kumar


2 Answers

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")
like image 121
Christos Chadjikyriacou Avatar answered Oct 07 '22 19:10

Christos Chadjikyriacou


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)")
like image 43
Duyen-Hoa Avatar answered Oct 07 '22 20:10

Duyen-Hoa