Latcie Latcie - 4 months ago 18
iOS Question

NSDateFormatter and stringFromDate

So, I have

let formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy MM dd"


And then I have

dateLabel.text = formatter.stringFromDate(currentDate!)


But when I do this:

(lldb) po dateLabel.text
▿ Optional<String>
- Some : "2016 01 17"

(lldb) po currentDate
▿ Optional<NSDate>
- Some : 2016-01-18 00:00:00 +0000


Obivously, conversion from 2016-01-18 to string results in 2016 01 17. Any ideas?

Answer

You need to refer to UTC timezone

    let dateString = "2016 01 17"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
    let s = dateFormatter.dateFromString(dateString)
    print(s)