swift 将日期字符串转换为其他格式

oyjwcjzk  于 2022-10-31  发布在  Swift
关注(0)|答案(1)|浏览(206)

我有myString“28-OCT-22”我需要将其转换为不同的格式“dd.MM.yyyy”我尝试过:

let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "d-MMM-yy"
                    let date = dateFormatter.date(from: myString)! //error, I think because OCT is uppercase, NSDateFormatter doesn't have this format?
                    dateFormatter.dateFormat = "dd.MM.yyyy"
                    let stringDate = dateFormatter.string(from: date)

还有更干净方法吗?

wbgh16ku

wbgh16ku1#

月份缩写已本地化。
将语言环境设置为支持OCT的固定通用值en_US_POSIX

let myString = "28-OCT-22"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "d-MMM-yy"
let date = dateFormatter.date(from: myString)!
dateFormatter.dateFormat = "dd.MM.yyyy"
let stringDate = dateFormatter.string(from: date)

尽管格式正确,但不建议强制展开转换后的日期

相关问题