在SWIFT中将NSDate转换为具有特定时区的String [英] Convert NSDate to String with a specific timezone in SWIFT
问题描述
在我的coredatabase中,我有一个带有NSDate属性的news实体。我的应用程序遍布全球。
In my coredatabase I have an "news" entity with a NSDate attribute. My app is worldwide.
新闻发布 2015-09-04 22:15:54 +0000 法国时间(GMT +2)
News was published 2015-09-04 22:15:54 +0000 French hour (GMT +2)
为了保存日期,我将其转换为UTC格式。
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)
新闻记录日期: 2015-09 -04 20:15:54 +0000 (UTC)
The news is recorded with the date : 2015-09-04 20:15:54 +0000 (UTC)
稍后在应用程序中,我需要转换保存在String中的NSDate:
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)
一切都很完美如果我在发布新闻时(即GMT + 2)在同一时区启动应用程序。
Everything works perfectly if I launch the app in the same timezone when I published the news i.e GMT+2.
如果我更改设备的时区,例如UTC-4,那么在String中转换我的NSDate,日期不一样。我得到了: 2015-09-04 16:15:54 +0000
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
如何获得与我的数据库相同的UTC日期时区?
How to obtain the same UTC date as in my database for any timezone?
我对时区不太满意,但我认为我的问题来自NSDate中的+0000。在我的所有日期,总有+0000,我认为它应该是正确的时区。但我不知道该怎么办。
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.
推荐答案
Xcode 8 beta•Swift 3.0
您的ISO8601日期格式是没有Z的基本hms。您需要使用xxxx表示+0000。
Your ISO8601 date format is basic hms without Z. You need to use "xxxx" for "+0000".
+ 0000表示UTC时间。
"+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:
这篇关于在SWIFT中将NSDate转换为具有特定时区的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!