Skip to main content

How to format dates inside text views

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to format dates inside text views 관련

SwiftUI by Example

Back to Home

How to format dates inside text views | SwiftUI by Example

How to format dates inside text views

Updated for Xcode 15

SwiftUI's text views come with two specific date formatters to make dates look better on screen: one to handle single dates, and one to handle date ranges.

The date range version is actually simpler, because you just provide a closed date range and it will make sure it's formatted appropriately according to the user's locale:

Text(Date.now...Date.now.addingTimeInterval(600))

Download this as an Xcode projectopen in new window

The text “2:37–2:47 PM”

For example, that might show “10:30AM-10:40AM”.

When working with single dates, you should provide a style parameter to accompany it to determine how the date should be formatted. Here are some options:

VStack {
    // show just the date
    Text(Date.now.addingTimeInterval(600), style: .date)

    // show just the time
    Text(Date.now.addingTimeInterval(600), style: .time)

    // show the relative distance from now, automatically updating
    Text(Date.now.addingTimeInterval(600), style: .relative)

    // make a timer style, automatically updating
    Text(Date.now.addingTimeInterval(600), style: .timer)
}

Download this as an Xcode projectopen in new window

The lines “June 29, 2021” and “2:49 PM”, as well as two lines counting down from 10 minutes reading “8 min, 14 sec”, and “8:14” respectively.
The lines “June 29, 2021” and “2:49 PM”, as well as two lines counting down from 10 minutes reading “8 min, 14 sec”, and “8:14” respectively.
Similar solutions…
How to format text inside text views | SwiftUI by Example

How to format text inside text views
How to let the user select multiple dates | SwiftUI by Example

How to let the user select multiple dates
How to format a TextField for numbers | SwiftUI by Example

How to format a TextField for numbers
How to force views to one side inside a stack using Spacer | SwiftUI by Example

How to force views to one side inside a stack using Spacer
How to draw a border inside a view | SwiftUI by Example

How to draw a border inside a view

이찬희 (MarkiiimarK)
Never Stop Learning.