In Swift, there are several ways to work with date formatting, such as DateComponentsFormatter and RelativeDateTimeFormatter.
DateComponentsFormatter
- Formats a time interval (duration) between two points in time.
- It doesn’t know whether it’s past or future, only the length of time.
- Example outputs:
2d,1 hour, 5 minutes,3h 15m - Use it for: durations, timers, countdowns, video lengths, etc.
RelativeDateTimeFormatter
- Formats a date relative to another date, automatically handling past or future.
- Adds natural language like “ago” or “in”.
- Example outputs:
2 days ago,in 3 hours,yesterday,tomorrow - Use it for: human-readable time expressions like “5m ago” or “in 2d”.
Quick Comparison
| Purpose | Formatter | Example |
|---|---|---|
| Duration (no direction) | DateComponentsFormatter |
2d, 3h 15m
|
| Relative time (with context) | RelativeDateTimeFormatter |
2 days ago, in 3 hours
|
Example of usage
DateComponentsFormatter:
private var abbreviatedFormatter: DateComponentsFormatter {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .hour, .day]
formatter.unitsStyle = .abbreviated
formatter.maximumUnitCount = 1
return formatter
}
func asAbbreviatedString() -> String {
let from = Date().timeIntervalSince(self)
return abbreviatedFormatter.string(from: from) ?? ""
}
RelativeDateTimeFormatter:
private var shortFormatter: RelativeDateTimeFormatter {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter
}
func asShortString() -> String {
return shortFormatter.localizedString(for: self, relativeTo: Date())
}
Pro tip
Create an extension and add these shorthand functions to it.
extension Date {
private var abbreviatedFormatter: DateComponentsFormatter {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .hour, .day]
formatter.unitsStyle = .abbreviated
formatter.maximumUnitCount = 1
return formatter
}
private var shortFormatter: RelativeDateTimeFormatter {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter
}
func asAbbreviatedString() -> String {
let from = Date().timeIntervalSince(self)
return abbreviatedFormatter.string(from: from) ?? ""
}
func asShortString() -> String {
return shortFormatter.localizedString(for: self, relativeTo: Date())
}
}
Top comments (0)