Swift version: 5.6
If you want to format dates and times in the form “5 hours ago” or “3 months ago”, Apple gives us a dedicated formatter called RelativeDateTimeFormatter
. This is localized for many languages, so you’ll automatically get back strings that work in French, German, Chinese, and more, all depending on the user’s locale.
Here’s an example to get you started:
// the date you want to format
let exampleDate = Date.now.addingTimeInterval(-15000)
// ask for the full relative date
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
// get exampleDate relative to the current date
let relativeDate = formatter.localizedString(for: exampleDate, relativeTo: Date.now)
// print it out
print("Relative date is: \(relativeDate)")
That will print “Relative date is: 4 hours ago”.
“Full” has a precise meaning here: we’ll get back things like “2 months ago”, and if you prefer you can try spell out mode to get “two months ago” or even short mode to get “2 mo. ago”.
Having that second relativeTo
parameter available allows us to calculate relative values between two arbitrary dates, rather than one date and the current date:
let relativeDate2 = formatter.localizedString(for: someDate, relativeTo: someOtherDate)
Tip: Although relative time formatters are great for things in recent history – the last few months, perhaps – they are less useful for larger time gaps. So, you might want to try checking whether your date is over six months ago, and if so use a custom formatter instead to give the specific date.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 13.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.