Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSDate to String with a specific timezone in SWIFT

In my coredatabase I have an "news" entity with a NSDate attribute. My app is worldwide.

News was published 2015-09-04 22:15:54 +0000 French hour (GMT +2)

To save the date, I convert it, in UTC format.

let mydateFormatter = NSDateFormatter()
mydateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+00:00"
mydateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
var dateToSaved : NSDate! = mydateFormatter.dateFromString(date)

The news is recorded with the date : 2015-09-04 20:15:54 +0000 (UTC)

Later in the app, I need to convert this NSDate saved in String:

let mydateFormatter = NSDateFormatter()
mydateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+00:00"
var dateInString:String = mydateFormatter.stringFromDate(date)

Everything works perfectly if I launch the app in the same timezone when I published the news i.e GMT+2.

If I change the timezone of my device, for example UTC-4, then convert my NSDate in String, the date is not the same. I got : 2015-09-04 16:15:54 +0000

How to obtain the same UTC date as in my database for any timezone?

I'm not very comfortable with timezone, but I think my issue comes from the "+0000" in the NSDate. In all my dates, there is always +0000, it should be the right timezone, I think. But I don't know how to do.

like image 624
cmii Avatar asked Dec 24 '22 14:12

cmii


1 Answers

Xcode 8 beta • Swift 3.0

Your ISO8601 date format is basic hms without Z. You need to use "xxxx" for "+0000".

"+0000" means UTC time.

let dateString = "2015-09-04 22:15:54 +0000"

let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(calendarIdentifier: .ISO8601)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx"
dateFormatter.locale = Locale(localeIdentifier: "en_US_POSIX")
if let dateToBeSaved = dateFormatter.date(from: dateString) {
    print(dateToBeSaved)   // "2015-09-04 22:15:54 +0000"
}

If you need some reference to create your date format you can use this:

enter image description here

like image 69
Leo Dabus Avatar answered Dec 31 '22 13:12

Leo Dabus