Wednesday, January 26, 2022 [Tweets] [Favorites]

Swift Foundation Formatter Improvements

Keith Harrison:

Unfortunately the documentation is not great so here’s a summary starting with date formatting.

[…]

In iOS 15 you apply the formatting directly to the Date without the need to create (and cache) a formatter. For example, the formatted(date:time) method applies predefined date and time styles[…]

[…]

You customize the output by adding fields to the style. The output then contains just the fields you want:

now.formatted(.dateTime.year().day().month()) // Jan 23, 2022

[…]

If you add the .attributed field to a format you get back a formatted attribute string. This is handy when you want to format components of the output[…]

The above example is for localized formatting, so the order that you specify the fields in doesn’t matter, and the styles and spellings are subject to the user’s settings.

To specify exactly the format that you want, there’s a new type-safe alternative to format strings. Instead of:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.string(from: date)

You can write:

date.formatted(Date.VerbatimFormatStyle(format: "\(year: .defaultDigits)-\(month: .twoDigits)-\(day: .twoDigits)", 
                                        timeZone: .current, 
                                        calendar: .current))

Yes, unfortunately this method leads to long code lines. And you probably still need to use Locale(identifier: "en_US_POSIX") to get dependable results.

Previously:

Update (2022-05-31): See also: Donny Wals.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment