"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.

ActivityView.swift
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

Gotchas

See also