简体   繁体   English

从 JSON 读取后快速重新格式化时间

[英]Swift- reformatting time after reading from JSON

I am trying to reformat the time that I am reading off from a String from a JSON API.我正在尝试重新格式化从 JSON API 中读取字符串的时间。 It is reading from the JSON fine because it gives me the result- the String "2020-05-12T00:00:00:00.000 How can I convert this string it is giving in to an NSDate because I have looked at previous questions and the solution they are giving me is giving me the error that leads to the string having a value of nil它正在从 JSON 中读取,因为它给了我结果 - 字符串“2020-05-12T00:00:00:00.000 如何将它提供给 NSDate 的这个字符串转换为 NSDate,因为我已经查看了之前的问题和他们给我的解决方案是给我导致字符串值为 nil 的错误

Try using following as format - "yyyy-MM-dd'T'HH:mm:ss:SS.SSS"尝试使用以下格式 - “yyyy-MM-dd'T'HH:mm:ss:SS.SSS”

let dateString = "2020-05-12T00:00:00:00.000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SS.SSS"
let date = dateFormatter.date(from: dateString)!
print(date)

// Prints Date object
// 2020-05-12 00:00:00 +0000

The last 00.000 tells us fractional of a second, which is represented by SS.SSS Refer to this page for more date formatter related queries.最后的 00.000 告诉我们秒的小数部分,由 SS.SSS 表示。有关更多与日期格式化程序相关的查询,请参阅页面。

Two things to note about the fractional second.关于小数秒有两点需要注意。 First, it does not round, it just shows the appropriate places (otherwise the 2 digit fractional second would show 7 ms as “01”).首先,它不四舍五入,它只显示适当的位置(否则 2 位小数秒将显示 7 ms 为“01”)。 Secondly, the Unicode standard lets you use as many as you want, so “SSSSS” is valid.其次,Unicode 标准让你想用多少就用多少,所以“SSSSS”是有效的。 However, DateFormatter will not show anything below milliseconds, it will just show 0s below that.但是,DateFormatter 不会显示低于毫秒的任何内容,它只会显示低于毫秒的 0。 So 123456789 nanoseconds with a “SSSSSSSSS” format string will show up as “123000000”因此,带有“SSSSSSSSS”格式字符串的 123456789 纳秒将显示为“123000000”

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

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