Date.FormatStyle from format text?

I really like Foundation's Date.FormatStyle API for formatting dates, and would like to know if they can be configured using an nsdateformatter.com-style format text (like back in the DateFormatter days).

I can see the appeal of the new API, but let's say our team uses a number of format texts to be aligned between multiple platforms. Can I just pass y-MM-dd to initialize a Date.FormatStyle?

1 Like

I had a similar case recently and my only solution was to format individual components and concatenate, something like: "\(date.format(yearFormat))-\(date.format(monthFormat))-\(date.format(dayFormat))"

1 Like

It sounds Date.VerbatimFormatStyle could work for you.

let verbatim = Date.VerbatimFormatStyle(
    format: "\(year: .defaultDigits)-\(month: .defaultDigits)-\(day: .defaultDigits)",
    locale: Locale(identifier: "en_US"),
    timeZone: .gmt,
    calendar: .current
)
3 Likes

Whoa, nice one. I thought I read through the documentation, obviously I didn't. Thank you!

Thanks for the hint! :clap:

I looked into the implementation a bit, and it turns out that VerbatimFormatStyle internally uses a formatPattern in the style I'm looking for, but doesn't expose it, probably for good reason.

I then tried to extend it like this:

extension Date.VerbatimFormatStyle {
  init(formatPattern: String, /* ... */) {
    self.formatPattern = formatPattern
    // ...
  }
}

Date.VerbatimFormatStyle(formatPattern: "EEEE, MMM d, yyyy", /* ... */)

...but since the formatPattern variable is internal, this won't compile.

I'll probably try to build my own type that conforms to FormatStyle and works like VerbatimFormatStyle, but has the formatPattern accessible directly.

(Or unsafeBitCast... :imp:)