更改 NSDate 格式化程序以将字符串转换为所需的样式

Change the NSDate formatter to convert string to desired style

如何将 1st Dec 1984 字符串值的日期格式化程序更改为 2022-12-01

所需的日期格式化程序样式是什么?

这个答案无论如何都不漂亮。但它会完成工作。困难的是 1st 中的 'st'。据我所知,没有日期格式。

let dateString = "1st Dec 1984".replacingOccurrences(of: "[st|nd|th|rd]", with: "", options: .regularExpression)
let formatter = DateFormatter()

formatter.dateFormat = "d MM yyyy"

let date = formatter.date(from: dateString)

formatter.dateFormat = "yyyy-MM-dd"

let newString = formatter.string(from: date!)

这会给你想要的结果。除了我不确定你如何在你的结果中得到 2022 年,因为从你给定的日期起永远不会产生它。