将ISO8601字符串转换为重新格式化的日期字符串(Swift)

时间:2017-06-18 10:31:38

标签: ios swift iso8601 dateformatter

我从JSON数据库中提取日期。日期格式为2017-06-16T13:38:34.601767(我认为是ISO8601)。我正在尝试使用ISO8601DateFormatter格式化2017-06-16T13:38:34.601767到2017-06-16的日期。到目前为止,我甚至无法将拉出的字符串格式化为日期。

let pulledDate = self.pulledRequest.date
var dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: pulledDate)
print(date!) //nil

我不确定我的日期格式是否错误且不是ISO8601,或者我没有按预期使用ISO8601DateFormatter。

1。)是否是ISO8601日期? 2.)我是否正确使用ISO8601DateFormatter?

谢谢!

1 个答案:

答案 0 :(得分:3)

ISO8601有几个不同的选项,包括时区。看来默认情况下private void loadImage(String path) { originalImage = Highgui.imread(path); Mat out = new Mat(); Log.i(TAG, "Number Of Channels: " + originalImage.channels()); Imgproc.cvtColor(originalImage, out, Imgproc.COLOR_GRAY2RGB); Log.i(TAG, "Number Of OUT Channels: " + out.channels()); } 需要字符串中的时区指示符。您可以使用自定义选项禁用此行为,如下所示:

ISO8601DateFormatter

如果您想知道默认选项是什么,只需在游乐场中运行此代码:

let pulledDate = "2017-06-16T13:38:34.601767"
var dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
let date = dateFormatter.date(from: pulledDate)

当然,如果您的字符串不包含时区,则日期格式化程序仍将使用其let dateFormatter = ISO8601DateFormatter() let options = dateFormatter.formatOptions options.contains(.withYear) options.contains(.withMonth) options.contains(.withWeekOfYear) options.contains(.withDay) options.contains(.withTime) options.contains(.withTimeZone) options.contains(.withSpaceBetweenDateAndTime) options.contains(.withDashSeparatorInDate) options.contains(.withColonSeparatorInTime) options.contains(.withColonSeparatorInTimeZone) options.contains(.withFullDate) options.contains(.withFullTime) options.contains(.withInternetDateTime) 属性在时区中对其进行解释,根据文档,该属性默认为GMT。

如果您想在不同的时区解释日期,请记得在使用格式化程序之前更改它:

timeZone
相关问题