我想解析一个yyyyMMdd格式的日期。
let strategy = Date.ParseStrategy(
format: "\(year: .defaultDigits)\(month: .twoDigits)\(day: .twoDigits)",
locale: Locale(identifier: "fr_FR"),
timeZone: TimeZone(abbreviation: "UTC")!)
let date = try? Date("20220412", strategy: strategy) // nil :(strategy有什么问题?
发布于 2022-04-12 08:53:55
问题是.defaultDigits不适用于这种日期格式的.year,原因很可能是因为该格式不包含分隔符,因此解析器无法自动推断用于年份部分的数字数。
如果我们试着用分离器,它会工作的很好。例如,yyyy
let strategy = Date.ParseStrategy(
format: "\(year: .defaultDigits)-\(month: .twoDigits)-\(day: .twoDigits)",
locale: Locale(identifier: "fr_FR"),
timeZone: TimeZone(abbreviation: "UTC")!)
if let date = try? Date("2022-04-12", strategy: strategy) { print(date) }版画
2022-04-12 00:00:00 +0000
没有分隔符的格式的解决方案是使用.padded显式地告诉策略年份部分包含多少位数字(另一个选项是.extended(minimumLength:))
let strategy = Date.ParseStrategy(
format: "\(year: .padded(4))\(month: .twoDigits)\(day: .twoDigits)",
locale: Locale(identifier: "fr_FR"),
timeZone: TimeZone(abbreviation: "UTC")!)
if let date = try? Date("20220412", strategy: strategy) { print(date) }再一次打印
2022-04-12 00:00:00 +0000
https://stackoverflow.com/questions/71839420
复制相似问题