Adam Rush

@Adam9Rush

29 March, 2022

Introduction

Using dates within your application will probably be necessary; in fact, most applications will need to use the date somehow.

Back in the Objective-C days, this was always a struggle, and developers would be overwhelmed with complexity within the DateFormatter class. We had a dedicated website to help with this complexity.

In SwiftUI, we have the Date() API to help with this, and it’s so straightforward than before with the added modifiers. However, Date() it is still the bridge from the Objective-C days, so do keep this in mind when using it in your application.

Displaying a Date() within a Text

In this article, we’re going to be displaying dates within a Text element; of course, you can use the Date() objects throughout the codebase in many scenarios, but you’re going to keep it simple.

VStack {
    Text(Date.now, style: .date)
}

In your example, you’re simply adding today’s Date and using the style .date which will show the following result:

A simple date formatter in your SwiftUI application

This is great for displaying a specific date that is easy to understand from a UI perspective.

VStack {
    Text(Date.now, style: .date)
    Text(Date.now, style: .relative)
}

You can style using .relative which will show the format increasing by the second.

You can see the time growing, and this is how incredible SwiftUI is because, under the hood, you’re getting updates on the time between now and in the future.

VStack {
    Text(Date.now, style: .date)
    Text(Date.now, style: .relative)
    Text(Date.now, style: .time)
}

You can also specify just the .time style, and you’ll get a nicely formatted time displayed:

Date formatters displayed in a SwiftUI application

These are super convenient to show the current date formatters in your application quickly.

It’s worth noting that this is an example on the different date formatters. If you want to display the correct date or time to your users, then you should consider exploring the Calendar library. This will make sure you correctly identify time and date based on certain regions and locations.

What’s Next?

In this article, you’ve explored using dates and various ways to display the time within your iOS SwiftUI application. As mentioned above, you should consider exploring the Calendar APIs provided by Apple to show the correct date or time.

You can read more about the Calendar here.

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.