Question about round-tripping with Date.ParseStrategy and Date.FormatStyle

I am working with a text file format that I do not have control over.

Dates are represented with strings like "2014_03_11" using an underscore to separate them rather than a space or a hyphen.

I am able to create a Date.ParseStrategy that parses the strings into dates:

let strategy = Date.ParseStrategy(
    format: "\(year: .defaultDigits)_\(month: .twoDigits)_\(day: .twoDigits)",
    timeZone: TimeZone.current)

I cannot seem to find a way to round-trip a date back to a string using an underscore as the separator using a Date.FormatStyle.

I seem to be able to specify each date component, but not how they are separated.

Is there a way to do this using Date.FormatStyle or some other piece of the most recent APIs? Or do I need to go back to using DateFormatter for this?

Thanks for any pointers or assistance.

    format: Date.FormatString("\(year: .padded(4))_\(month: .twoDigits)_\(day: .twoDigits)"),
    timeZone: .current,
    calendar: .current
))) // 2024_03_12
1 Like

Thank you @tera!

I never would have guessed the name 'VerbatimFormatStyle" in order to search for it.

1 Like

Yeah, autocomplete doesn't quite help here either, only when you know the answer partially already.

Beware of the calendar / timezone and the missing (defaulted) locale parameters. e.g. if the calendar is set to Chinese things won't be formatted the way you expect.

1 Like

Thank you, yes, I'll be setting the calendar, time zone, and locale explicitly.

1 Like