Monday, June 29, 2026
HomeiOS DevelopmentFormatting dates in Swift utilizing Date.FormatStyle on iOS 15 – Donny Wals

Formatting dates in Swift utilizing Date.FormatStyle on iOS 15 – Donny Wals

[ad_1]

Revealed on: Could 27, 2022

Working with dates isn’t simple. And displaying them to your customers within the appropriate locale hasn’t at all times been simple both. With iOS 15, Apple launched a brand new technique to convert Date objects from and to String. This new means comes within the type of the brand new Formatter api that replaces DateFormatter.

As any seasoned iOS developer will inform you, DateFormatter objects are costly to create, and therefor form of tedious to handle appropriately. With the brand new Formatter api, we now not have to work with DateFormatter. As a substitute, we are able to ask a date to format itself based mostly on our necessities in a extra performant, simpler to make use of means.

On this put up I’ll present you how one can convert Date objects to String in addition to how one can extract a Date from a String.

Changing a Date to a String

Probably the most easy technique to convert a Date to a String is the next:

let formatted = Date().formatted() // 5/26/2022, 7:52 PM

By default, the formatted() perform makes use of a compact configuration for our String. The way in which formatted() converts our Date to String takes under consideration the consumer’s present locale. For instance, if my machine was set to be in Dutch, the date can be formatted as 26-5-2022 19:54 which is a extra applicable formatting for the Dutch language.

Nonetheless, this may not at all times be what we want. For instance, we would wish to have our date formatted as Could 26 2022, 7:52 PM. We will use the next code to do this:

let formatted = Date().formatted(
    .dateTime
        .day().month(.extensive).12 months()
        .hour().minute()
)

Let’s break this code aside a bit. The formatted perform takes an object that conforms to the FormatStyle protocol as its argument. There are numerous methods for us to create such an object. The FormatStyle protocol has a number of handy extensions that may present us with a number of completely different formatters.

For instance, when sending a Date to a server, we’ll typically have to ship our dates as ISO8601 compliant strings. Earlier than I clarify the code you simply noticed, I wish to present you the right way to seize an ISO8601 compliant string from the present Date.

let formatted = Date().formatted(.iso8601) // 2022-05-26T18:06:55Z

Neat, huh?

Okay, again to the instance from earlier than. The .datetime formatter is used as a foundation for our customized formatting. We will name varied capabilities on the item that’s returned by the .datetime static property to pick out the data that we wish to present.

A few of these properties, just like the month, could be configured to specify how they need to be formatted. Within the case of .month, we are able to select the .extensive formatting to spell out the total month identify. We might use .slim to abbreviate the month all the way down to a single letter, or we might use one of many different choices to characterize the month in numerous methods.

Should you omit a property, like for instance .12 months(), our formatted date will omit the 12 months that’s embedded within the Date. And once more, the underlying formatter will at all times mechanically respect your consumer’s locale which is absolutely handy.

One other technique to format the date is to by specifying the way you need the date and time to be formatted respectively:

let formatted = Date().formatted(date: .full, time: .commonplace) // Thursday, Could 26, 2022, 8:15:28 PM

The above offers a really verbose formatted string. We will make a extra compact one utilizing the next settings:

let formatted = Date().formatted(date: .abbreviated, time: .shortened) // Could 26, 2022, 8:16 PM

It’s even doable to omit the date or time solely by utilizing the .omitted choice:

let formatted = Date().formatted(date: .abbreviated, time: .omitted) // Could 26, 2022

There are tons of various combos you may provide you with so I extremely advocate you discover this api some extra to get a way of how versatile it truly is.

Making a Date from a String

Changing String to Date is barely much less handy than going from a Date to a String but it surely’s nonetheless not too dangerous. Right here’s how you may cowl the frequent case of changing an ISO8601 compliant string to a Date:

let string = "2022-05-26T18:06:55Z"
let expectedFormat = Date.ISO8601FormatStyle()
let date = strive! Date(string, technique: expectedFormat)

We make use of the Date initializer that takes a string and a formatting technique that’s used to parse the string.

We will additionally use and configure an occasion of FormatStyle to specify the elements that we anticipate to be current in our date string and let the system parse it utilizing the consumer’s locale:

let string = "Could 26, 2022, 8:30 PM"
let expectedFormat = Date.FormatStyle()
    .month().12 months().day()
    .hour().minute()
let date = strive! Date(string, technique: expectedFormat)

The order of our date elements doesn’t matter; they may mechanically be rearranged to match the consumer’s locale. That is tremendous highly effective, but it surely does imply that we are able to’t use this to parse dates on gadgets that use a special locale than the one which matches the string’s locale. The very best locale agnostic date string is ISO8601 so in case you have management over the date strings that you simply’ll parse, be sure to use ISO8601 when doable.

Abstract

On this brief article, you realized how you should utilize iOS 15’s FormatStyle to work format Date objects. You noticed the right way to go from Date to String, and the opposite means round. Whereas FormatStyle is extra handy than DateFormatter, it’s iOS 15 solely. So for those who’re nonetheless supporting iOS 14 you’ll wish to be certain to take a look at DateFormatter too.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments