"5 minutes ago" and live countdowns in SwiftUI
Text can show relative dates and run timers by itself. No Timer, no publishers, no string building.
iOS 16+macOS 13+ Swift 5.9
Showing “posted 5 minutes ago” or a countdown to a deadline usually starts with a Timer that fires every second and rebuilds a string. SwiftUI’s Text can do both on its own, and the system keeps it up to date, even in widgets.
import SwiftUI
struct ActivityView: View {
let posted = Date.now.addingTimeInterval(-5 * 60)
@State private var deadline = Date.now.addingTimeInterval(90)
var body: some View {
VStack(alignment: .leading, spacing: 12) {
// "5 minutes ago", "yesterday", "last week", refreshed every 30 seconds
TimelineView(.periodic(from: .now, by: 30)) { _ in
Text(posted, format: .relative(presentation: .named, unitsStyle: .wide))
}
// A live countdown, "1:29", "1:28", ..., stopping at 0:00
Text(timerInterval: Date.now...deadline, countsDown: true)
.font(.largeTitle.monospacedDigit())
// Elapsed time that keeps counting: "5 minutes, 3 seconds"
Text(posted, style: .relative)
}
.padding()
}
}
#Preview {
ActivityView()
}How it works
Text(_:style:)with.relative,.timeror.offsetis updated by the system, not by your view. It keeps counting while the rest of the view stays still, which is why it also works in widgets and Live Activities.Text(timerInterval:countsDown:)shows a clock-style timer for a range of dates and stops at the end of the range. PasspauseTime:to freeze it..relative(presentation:unitsStyle:)is aFormatStyle, so it gives the friendliest wording (“yesterday”, “in 2 hours”), but it is formatted once. Wrapping it in aTimelineViewre-renders it on a schedule you choose.
Gotchas
.namedgives words such as “yesterday”;.numericalways gives numbers (“1 day ago”). Pick per screen, not per value.Text(date, style: .relative)has no “ago”. It shows the distance only, so put it in a sentence:Text("Posted \(posted, style: .relative) ago").- Build the range for
Text(timerInterval:)from stored dates. A range made fromDate.nowinsidebodyrestarts every time the view updates. - A
TimelineViewthat refreshes every second for a label that changes every minute wastes battery. Match the period to the precision you show.