我正在使用字符串扩展函数来转换日期字符串。该功能是:SWIFT DateFormatter结果不一致
func convertDateString() -> String {
let dateFormater = DateFormatter()
var returnString = ""
dateFormater.dateFormat = "yyyy-MM-dd'T'hh:mm:ss'Z'" // Takes the format from the JSON journal entry for elite dangerous
dateFormater.locale = Locale.current
if let dateObj = dateFormater.date(from: self) {
dateFormater.dateFormat = "dd MMM yyyy hh:mm:ss" // Converts it to a new string (as a date object)
returnString = dateFormater.string(from: dateObj) // Converts the date object back to a string
} else {
returnString = "Error converting date"
}
return returnString
}
我使用的数据集这是一个系列的JSON对象调用的字符串延伸的结果的一部分从JSON参考文件转换的。
我正在两台机器上工作 - 一台MACPRO和一台MacBookAir。两者都运行相同版本的MacOS(10.12.5)和相同版本的Xcode。
当我在MACPRO上运行应用程序时,它会解析JSON对象文件而不会出现问题,并按照上述函数中的预期正确转换每个日期。但是,当我在MacBookAir上运行应用程序时,在完全相同的数据文件上,JSON对象文件似乎在没有问题的情况下被解析,但是某些(几个百分比)的日期不会按预期进行转换 - 它们会失败if let dateObj = dateFormater.date(from: self)
语句和作为“错误转换日期”返回。
我不知道发生了什么。我曾尝试删除dateFormater.locale = Locale.current
,这没有什么区别。
相同的JSON对象产生错误(即每次运行文件时,它都是产生“错误转换日期”响应的相同JSON对象)。当我在文本编辑器中查看JSON对象文件时,JSON对象似乎没有问题(我也在一个在线JSON对象格式化程序中确认了这一点,并且它正确读取了JSON对象。)
我也应该补充说我正在使用SwiftyJSON来解析JSON对象。
任何帮助或建议感激地收到。
有没有办法让我的代码更健壮?任何人都可以提出,为什么不同的机器可能会有所作为,因为应用程序的数据文件,Xcode和MacOS都是一样的。
Apple在[本文](https://developer.apple.com/library/content/qa/qa1480/_index.html)中写了类似的问题。如果你的目标是OS X 10.12及以上版本,请使用['ISO8601DateFormatter'](https://developer.apple.com/reference/foundation/nsiso8601dateformatter) –
你应该在你的问题中包含有问题的字符串。 – rmaddy
你不应该去看Z.hh是错误的(这是12h格式)。你需要使用HH(00-23)。并将你的格式化区域设置为'“en_US_POSIX”'。你应该检查这个https://stackoverflow.com/questions/28016578/swift-how-to-create-a-date-time-stamp-and-format-as-iso-8601-rfc-3339-utc-tim/ 28016692#28016692 –