Convert NSDate to String with a specific timezone in SWIFT

北慕城南 提交于 2019-11-27 22:36:20

问题


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.


回答1:


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:



来源:https://stackoverflow.com/questions/32406520/convert-nsdate-to-string-with-a-specific-timezone-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!