gpt4 book ai didi

ios - 如何快速将 "2017-07-11T06:52:15.948Z"转换为类似 "JUL, 7 2017"

转载 作者:搜寻专家 更新时间:2023-10-31 21:56:18 25 4
gpt4 key购买 nike

我正在尝试将字符串转换为日期,然后再次将日期转换为字符串。

我在下面尝试过,但它给了我一个零值错误

let string = "2017-07-11T06:52:15.948Z"

let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale // save locale temporarily
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: string)!
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.locale = tempLocale // reset the locale
let dateString = dateFormatter.string(from: date)
print("EXACT_DATE : \(dateString)")

然后我尝试通过像下面这样分隔确切的字符串来仅使用没有时间的日期

let string = "2017-07-11T06:52:15.948Z"
let dateonly = (string.components(separatedBy: "T"))[0]
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-mm-dd"
dateformatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
let date = dateformatter.date(from: dateonly!)

print(date ?? "no date ")


dateformatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateformatter.string(from: date!) //pass Date here
print(newDate)

这很好用。但是告诉我错误的月份

希望得到你的帮助

最佳答案

出于引用目的,我从 here 中获取了附加毫秒的答案 SSS

只是改变日期格式

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

完整代码

   let string = "2017-07-11T06:52:15.948Z"
let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale // save locale temporarily
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: string)!
dateFormatter.dateFormat = "MMM d, yyyy" ; //"dd-MM-yyyy HH:mm:ss"
dateFormatter.locale = tempLocale // reset the locale --> but no need here
let dateString = dateFormatter.string(from: date)
print("EXACT_DATE : \(dateString)")

输出

enter image description here

关于ios - 如何快速将 "2017-07-11T06:52:15.948Z"转换为类似 "JUL, 7 2017",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45081209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com