简体   繁体   English

在SWIFT中将NSDate转换为具有特定时区的String

[英]Convert NSDate to String with a specific timezone in SWIFT

In my coredatabase I have an "news" entity with a NSDate attribute. 在我的coredatabase中,我有一个带有NSDate属性的“news”实体。 My app is worldwide. 我的应用是全世界的。

News was published 2015-09-04 22:15:54 +0000 French hour (GMT +2) 新闻发布2015-09-04 22:15:54 +0000法国小时(GMT +2)

To save the date, I convert it, in UTC format. 为了保存日期,我将其转换为UTC格式。

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) 新闻记录日期: 2015-09-04 20:15:54 +0000 (UTC)

Later in the app, I need to convert this NSDate saved in String: 稍后在应用程序中,我需要将此NSDate转换为保存在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 ie GMT+2. 如果我在发布新闻即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. 如果我更改设备的时区,例如UTC-4,然后在String中转换我的NSDate,则日期不一样。 I got : 2015-09-04 16:15:54 +0000 我得到了: 2015-09-04 16:15:54 +0000

How to obtain the same UTC date as in my database for any timezone? 如何在任何时区获取与我的数据库相同的UTC日期?

I'm not very comfortable with timezone, but I think my issue comes from the "+0000" in the NSDate. 我对时区不太满意,但我认为我的问题来自NSDate中的“+0000”。 In all my dates, there is always +0000, it should be the right timezone, I think. 在我的所有日​​期,总有+0000,我认为它应该是正确的时区。 But I don't know how to do. 但我不知道该怎么做。

Xcode 8 beta • Swift 3.0 Xcode 8 beta•Swift 3.0

Your ISO8601 date format is basic hms without Z. You need to use "xxxx" for "+0000". 您的ISO8601日期格式是没有Z的基本hms。您需要使用“xxxx”表示“+0000”。

"+0000" means UTC time. “+0000”表示UTC时间。

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: 如果您需要一些参考来创建日期格式,您可以使用:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM