Displaying Relative Dates

SwiftUI makes relative date formatting effortless. Show "2 minutes ago" instead of timestamps with a single modifier.
Follow along with the code: iOS-Practice on GitHub
The Text Date Style
SwiftUI's Text view has built-in date formatting:
Text(date, style: .relative)
// Shows: "2 minutes ago", "1 hour ago", "3 days ago"
The view updates automatically as time passes.
Common Date Styles
// Relative time
Text(date, style: .relative) // "2 hours ago"
// Time only
Text(date, style: .time) // "3:45 PM"
// Date only
Text(date, style: .date) // "June 15, 2024"
// Timer (counts up or down)
Text(date, style: .timer) // "2:34:56"
// Offset from now
Text(date, style: .offset) // "+2 hours" or "-30 minutes"
Using in Lists
Perfect for showing when content was created or updated:
struct PostRowView: View {
let post: Post
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(post.title)
.font(.headline)
Text(post.body)
.font(.subheadline)
.foregroundColor(.secondary)
.lineLimit(2)
HStack {
Label("\(post.likes)", systemImage: "heart.fill")
.foregroundColor(.red)
.font(.caption)
Spacer()
Text(post.createdAt, style: .relative)
.font(.caption)
.foregroundColor(.secondary)
}
}
}
}
Last Refresh Indicator
Show when data was last fetched:
@State private var lastRefresh: Date?
var body: some View {
List {
if let lastRefresh = lastRefresh {
Section {
HStack {
Text("Last updated")
Spacer()
Text(lastRefresh, style: .relative)
.foregroundColor(.secondary)
}
.font(.caption)
}
}
// ... rest of list
}
}
private func loadData() async {
// ... load data ...
lastRefresh = Date()
}
Combining Styles
Show both date and relative time:
VStack(alignment: .trailing) {
Text(date, style: .date)
.font(.caption)
Text(date, style: .relative)
.font(.caption2)
.foregroundColor(.secondary)
}
Custom Formatting
For more control, use a DateFormatter:
struct DateView: View {
let date: Date
var body: some View {
Text(date, formatter: relativeDateFormatter)
}
private var relativeDateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.doesRelativeDateFormatting = true
return formatter
}
}
// Shows: "Today", "Yesterday", "June 15, 2024"
Interview Tip
The .relative style is SwiftUI-native and updates automatically. No timers or manual refresh needed—the system handles it efficiently.