How to display time ago from a date in Swift

How to display time ago from a date in Swift

Two approaches to display relative time in Swift: the built-in RelativeDateTimeFormatter for Swift 5.1+ and a manual implementation for older versions.

3 min de lecture
Julien Karst
swiftiosdate-formatting

How to display time ago from a date in Swift

In this short article we will see how you can display the time ago from a given date. This can be useful inside a chat or inside a social network application.

Using RelativeDateTimeFormatter (Swift 5.1)

Since Swift 5.1 Apple provide a new formatter called RelativeDateTimeFormatter. With that API you are able to display a relative date in a human readable format. This formatter also support localization.

Here a code example:

let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full

let now = Date()

// 2 hours ago
let twoHoursAgo = Calendar.current.date(byAdding: .hour, value: -2, to: now)!
let result = formatter.localizedString(for: twoHoursAgo, relativeTo: now)
print(result) // "2 hours ago"

You can also change the unitsStyle to .abbreviated to have a shorter result.

Manual implementation (Swift 3/4)

Before Swift 5.1 you need to do it manually. Here is a simple extension to handle this:

extension Date {
    func timeAgoDisplay() -> String {
        let calendar = Calendar.current
        let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
        let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())!
        let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())!
        let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!

if minuteAgo < self {
            let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0
            return "\(diff) sec ago"
        } else if hourAgo < self {
            let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0
            return "\(diff) min ago"
        } else if dayAgo < self {
            let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0
            return "\(diff) hrs ago"
        } else if weekAgo < self {
            let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0
            return "\(diff) days ago"
        }
        let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0
        return "\(diff) weeks ago"
    }
}

This extension on Date gives you a timeAgoDisplay() method that returns a human readable string like "2 hrs ago" or "3 days ago" depending on how far back the date is.

Julien Karst

Tech Lead & Développeur Full-Stack passionné par la création d'expériences numériques exceptionnelles.