ios - 在 SWIFT 中将 NSDate 转换为具有特定时区的字符串

标签 ios swift timezone nsdate nsdateformatter

在我的核心数据库中,我有一个带有 NSDate 属性的“新闻”实体。我的应用程序遍布全局。

新闻发表于2015-09-04 22:15:54 +0000法国时间(GMT +2)

为了保存日期,我将其转换为 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)

新闻记录日期:2015-09-04 20:15:54 +0000 (UTC)

稍后在应用程序中,我需要转换保存在字符串中的这个 NSDate:

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

如果我在发布新闻时的同一时区(即 GMT+2)启动应用程序,一切都会完美运行。

如果我更改我设备的时区,例如 UTC-4,然后将我的 NSDate 转换为字符串,日期就不一样了。我得到了:2015-09-04 16:15:54 +0000

如何为任何时区获取与我的数据库中相同的 UTC 日期?

我对时区不太满意,但我认为我的问题来自 NSDate 中的“+0000”。在我所有的日期中,总是有 +0000,我认为它应该是正确的时区。但我不知道该怎么做。

最佳答案

Xcode 8 测试版 • Swift 3.0

您的 ISO8601 日期格式是没有 Z 的基本 hms。您需要为“+0000”使用“xxxx”。

"+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"
}

如果你需要一些引用来创建你的日期格式,你可以使用这个:

enter image description here

关于ios - 在 SWIFT 中将 NSDate 转换为具有特定时区的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32406520/

相关文章:

ios - UIPickerView 的默认状态?

java - 在 Java 中将日期从 UTC 转换为 PST

java - 夏令时中的 DateUtils.addDays() 类问题

ios - 通过 iOS 8 Widget 断开蓝牙设备

ios - 在 iOS 应用程序上使用 Google map (应用程序评论)

ios - connect Action 在 iOS 开发中有什么作用?

javascript - 正在读回 HTML 输入日期 "incorrectly"

ios - 使用 WKScriptMessageHandler 时内存泄漏

ios - 如何像 iPhone 设置搜索栏一样打开 UISearchBar?

ios - 当状态更改时,如何防止 SceneKit 场景重新渲染不佳?