1

I wish to add the era to a date string formatted by Swift's DateFormatter in a locale-sensitive fashion (e.g. "6 Shevat 5780 AM"). I know that I can do:

func dateString(calendar: Calendar, date: Date = Date()) -> String {
    let df = DateFormatter()

    // EITHER
    df.dateStyle = .full // Locale sensitive, but does not include (current) era
    df.timeStyle = .none
    // OR
    df.dateFormat = "d MMMM yyyy G" // Not locale sensitive

    df.calendar = calendar
    return df.string(from: date)
}

...but one way doesn't include the era, the other presumes a date month year ordering.

Any clues, anyone?

Grimxn
  • 22,115
  • 10
  • 72
  • 85
  • 1
    Have you tried [`dateFormat(fromTemplate:options:locale:)`](https://developer.apple.com/documentation/foundation/dateformatter/1408112-dateformat) ? “Returns a localized date format string representing the given date format components arranged appropriately for the specified locale.” – Martin R Feb 01 '20 at 15:40
  • You can’t use dateFormat with date and/or time styles together. It should be one or another. For localized dates you can check this post https://stackoverflow.com/questions/28332946/how-do-i-get-the-current-date-in-short-format-in-swift/28347285 – Leo Dabus Feb 01 '20 at 15:47
  • @MartinR - fantastic! That's exactly what I was after. I assumed it would be an instance method I was looking for, not a class method. Many thanks. Post it as an answer, and I'll accept it. – Grimxn Feb 01 '20 at 16:25
  • @LeoDabus - I'm well aware of that. It was an artifice of the question, to save having two blocks for people to compare. What I really wanted was .timeStyle = .none; .dateStyle = .reallyFull. – Grimxn Feb 01 '20 at 16:28
  • @Grimxn: Well, its not really new, see for example https://stackoverflow.com/a/40425996/1187415 or https://stackoverflow.com/a/41622365/1187415. – Martin R Feb 01 '20 at 18:41

0 Answers0