Reputation: 1869
I'm having a real struggle with date formatting. I want to completely ignore timezone, as all times are considered local. I tried this in a playground and it works fine.
var dateFormatter: NSDateFormatter = NSDateFormatter()
var dateString = "2015-09-02 22:05:00"
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//dateFormatter.timeZone = NSTimeZone.localTimeZone()
let openDate = dateFormatter.dateFromString(dateString)
The above code creates a date value of "Sep 2, 2015, 10:05 PM", which is exactly what I want. However, when I copy and paste the same code into a simple project, the value always comes back as "2015-09-03 04:05:00 +0000", which is exactly what I don't want. I want the date to always be as if I am in the same timezone as it was saved in, regardless of where I am now.
Is there any way I can get it to completely ignore time zones? I want to save a date locally and retrieve it locally, but it keeps changing the time on me. Setting timezone in the date formatter makes no difference. Why does it work in playground but not in project? Thanks.
Upvotes: 1
Views: 139
Reputation: 236350
You can ignore timezone treating your date as UTC time as follow:
let dateFormatter: NSDateFormatter = NSDateFormatter()
let dateString = "2015-09-02 22:05:00"
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
if let dateFromString = dateFormatter.dateFromString(dateString){
println(dateFromString) // "2015-09-02 22:05:00 +0000"
let stringFromDate = dateFormatter.stringFromDate(dateFromString)
println(stringFromDate) // "2015-09-02 22:05:00"
}
Upvotes: 1
Reputation: 118671
NSDate adopts the NSCoding protocol, and can be placed directly in NSUserDefaults, so you shouldn't have to worry about serialization at all.
Upvotes: 0