Tuesday, June 28, 2022
HomeWeb DevelopmentMethods to use DateFormatter in Swift

Methods to use DateFormatter in Swift


Dates and occasions are an important a part of programming. They assist us observe information situations and permit us to prepare datasets chronologically.

Regardless of their significance, date and time formatting and interpretation aren’t all the time as simple as one would hope.

For instance, if the date in New York Metropolis is 05/03/2022 and the time is 3:20 PM, the common New Yorker would say that it’s Could third, 2022 at 3:20 within the afternoon. Nonetheless, that very same date and time would learn a lot otherwise to somebody in London, the place they’d interpret that date as March fifth, 2022 and say the time is eighteen:20.

These variations are resulting from three main elements: time zone (Japanese Commonplace Time vs. British Summer season Time); date format (month/day/12 months vs. day/month/12 months); and clock sort distinction (the USA makes use of the 12-hour clock, and, although London can use each, their authorities paperwork sometimes use the 24-hour clock).

These are just some date and time variations between two cities, however think about the variations throughout all of the world’s international locations (and even variations inside international locations).

That’s why if you need your app to be as accessible as attainable, it’s good to have logic in place to precisely signify dates and occasions in codecs which can be understood by completely different environments.

On this put up, I’ll present you tips on how to format your dates with Swift’s DateFormatter, in addition to with another present libraries. First, let’s get began with DateFormatter.

Organising our surroundings

Earlier than we start, let’s get ourselves arrange. Create a brand new Swift utility and open it in Xcode.

Subsequent, go to your ContentView.swift file and, outdoors the physique, instantiate new Date and DateFormatter objects.

let date = Date();
let dateFormatter = DateFormatter();

Date will give us the present date and time with respect to our present time zone. For me, it’s Wednesday, June 1st, 2022.

dateFormatter is an occasion of the DateFormatter class that enables us to function varied formatting features on our date. That is vital as a result of we will be unable to indicate date in a Textual content view with out correctly formatting it first. Let’s take a look at how we will format it within the physique of our ContentView.

​​var physique: some View {
        dateFormatter.dateStyle = .quick
        return Textual content(dateFormatter.string(from: date))
            .padding()
}

The above code will abbreviate the date and put it in numeric kind. For instance, in the present day’s date for me (June 1, 2022) will turn into 6/1/22.

Implementing DateFormatter

To start utilizing DateFormatter, we have to assign the type we would like. The .quick type that we’re assigning renders date in a numeric, or shortened, format. Which means that the month, day, and 12 months are represented as numbers. Additionally word that the 12 months is just two numbers as an alternative of a full 4.

Then, .string permits us to transform date to a string sort (which is what our Textual content view requires). It’s styled in line with dateFormatter, which is .quick in our case.

What if we needed to indicate the date with the month as an abbreviated string, the day as a quantity, and the 12 months as the total 4 digits? That’s straightforward! We’d use .medium as an alternative of .quick.

And what if we needed to indicate the date with the total month identify, a numeric day, and the total 12 months?

You guessed it, we’d use .lengthy.

We will take this even additional utilizing .full, which provides us the day of the week, the total month identify, a quantity for the day, and the total 12 months. You may see all of them under.

DateFormatter Style Examples

Making use of timeStyle

For those who additionally needed to show the time, you could possibly apply timeStyle to dateFormatter. This feature is utilized equally to dateStyle within the sense which you could nonetheless use the inbuilt .quick,.medium, .lengthy, and .full codecs.

You assign timeStyle like so:

dateFormatter.timeStyle = .quick

For those who add the above line after dateFormatter.dateStyle, it provides the shortened time to your date. You may see the result of this under:

Date And Time

This instance demonstrates the dateStyle as .full and the timeStyle as .quick.

Listed here are the opposite time types:

Other Time Styles

N.B., The occasions proven above are a bit completely different than the earlier examples, because it took me a while to vary the timeStyle.

Utilizing dateFormat

Along with setting the dateStyle and timeStyle, we will additionally use dateFormat. We’ll present a string that represents the date and time format we would like.

Let’s instantiate one other DateFormatter occasion known as dateFormatter2. This time, let’s use dateFormat as an alternative of dateStyle and timeStyle. See under:

dateFormatter2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" 

     …

Textual content(dateFormatter2.string(from: date))
                .padding(.backside)

Now let’s see how this appears within the UI:

DateFormatter With DateFormat

Excellent!

Styling the date

Let’s break dateFormat down for readability, beginning with the date.

The 12 months (yyyy) is 2022. We used the total 12 months, however if you wish to simply show “22”, you should use yy.

The month (MM) is 06, comparable to June. If you wish to show the month with out the 0, simply depart it as M. In order for you the month as a string, put MMMM.

Lastly, the day (dd) is 01. If you wish to show the day with out the 0 in entrance, simply depart it as D.

Styling the time

To format hours, or HH, you’ve got two choices. The primary is leaving the time formatted as HH, which aligns to the 24-hour time scale. The second choice is to make use of the 12-hour scale, and to take action you’d simply want to exchange it with H.

mm represents minutes and ss represents seconds. These are pretty self-explanatory.

To alter the order of those numbers, merely put them in numerous elements of the string. For instance, "MM-dd-yyyy'T'h:mm:ss" will seem like 06-01-2022T5:48:55.

Thus far so good! We will now use DateFormatter to format our dates and occasions utilizing the offered codecs or our personal string.

There’s just one caveat. Keep in mind what I discussed about completely different international locations, cities, continents, and extra having completely different time zones and date types? If solely there was a method that we may format our dates primarily based on the place we’re on the planet…

…and the excellent news is we will! That is attainable due to localization.

Utilizing localization with date and time formatting

Localization makes use of locales, units of parameters used to outline a person’s location, language and syntax. That is vital if you wish to make an app usable in a number of areas all through the world.

Localization goes past translating. When you may have the ability to use a language API to translate “June 1” in English to “juni 15” in Dutch to be used within the Netherlands, that is nonetheless technically incorrect when it comes to locale.

Within the Netherlands, individuals learn dates with the day previous the month. Technically, “June 1” ought to be localized to “1 juni.”

The excellent news is that DateFormatter handles a number of this for us already. Nonetheless, we will manually replace our DateFormatter’s locale by manipulating its locale property.

This property determines the locale for our formatter. If we don’t change this property, the locale used will probably be American English (represented by “en_us” in Swift).

If we needed to make use of the Netherlands as our locale, we will set the worth like so:

dateFormatter2.locale = Locale(identifier: "nl")

Let’s see what our date appears like with our new locale.

Date With Netherlands Locale

Excellent! This fashion, we accomplish not solely the language change but in addition the locale formatting. This creates a extra correct date total.

Conclusion

Date formatting in Swift may be easy proper out of the field, however we now have varied choices for flexibility and customization. Some circumstances might name for a extra abbreviated date, and others might name for an extended date.

You may additionally discover that displaying the month as a string is extra palatable or cohesive to your app than the quantity. You can even higher accommodate international customers by implementing localization, making your app really feel extra acquainted to them.

Time is our most respected asset. The least we will do is format it successfully.

All the accompanying code for this put up may be discovered on GitHub.

: Full visibility into your net and cellular apps

LogRocket is a frontend utility monitoring resolution that permits you to replay issues as in the event that they occurred in your personal browser. As a substitute of guessing why errors occur, or asking customers for screenshots and log dumps, LogRocket allows you to replay the session to shortly perceive what went fallacious. It really works completely with any app, no matter framework, and has plugins to log extra context from Redux, Vuex, and @ngrx/retailer.

Along with logging Redux actions and state, LogRocket information console logs, JavaScript errors, stacktraces, community requests/responses with headers + our bodies, browser metadata, and customized logs. It additionally devices the DOM to report the HTML and CSS on the web page, recreating pixel-perfect movies of even probably the most advanced single-page net and cellular apps.

.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments