I would like to parse a yyyyMMdd
formatted date.
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 :(
What is wrong with the strategy
?
CodePudding user response:
The problem is that .defaultDigits
doesn't work for .year
with this date format, the reason is most likely because the format doesn't contain a separator so the parser can't automatically deduce the number of digits used for the year part.
If we try with a separator it will work fine. For example yyyy-MM-dd
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) }
prints
2022-04-12 00:00:00 0000
The solution for your format without a separator is to explicitly tell the strategy how many digits the year part contains using .padded
(another option is .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) }
again prints
2022-04-12 00:00:00 0000