JulienKarst.

Navigate back to the homepage

How to display time ago from a date in Swift (This is how to get the difference between two dates in a string)

Julien Karst
June 24th, 2020 · 1 min read

How to display time ago from a date in Swift ?

Using Swift 5.1

This is how you can display time ago easily with Swift 5.1:

When iOS13 was released Apple introduce a new class RelativeDateTimeFormatter

1extension Date {
2 func timeAgoDisplay() -> String {
3 let formatter = RelativeDateTimeFormatter()
4 formatter.unitsStyle = .full
5 return formatter.localizedString(for: self, relativeTo: Date())
6 }
7 }

This class will allow you to get a time ago string based on your language. It automatically select the right unit of time based on your interval, here is an example:

1|--------------------------|------------------|
2| Time interval in seconds | Display |
3|--------------------------|------------------|
4| -6 | 6 seconds ago |
5| -60 | 1 minute ago |
6| -600 | 10 minutes ago |
7| -6000 | 1 hour ago |
8| -60000 | 16 hours ago |
9|--------------------------|------------------|

You’ll notice that it handle automatically plurals for you ! So you do not have to care about it. This feature is really useful if you are building a chat for example.

Using Swift 3 or Swift 4

In order to get the number of seconds we need to check if we have one minute or less, you can write that to get the current date minus one minute:

1let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!

Now we will compare those 2 dates now! (We replace yourDate by self) and get the difference between those 2 dates.

1if (minuteAgo < yourDate) {
2 let diff = Calendar.current.dateComponents([.second], from: yourDate, to: Date()).second ?? 0
3 print("\(diff) sec ago")
4 }

That’s it, you are now about to display time ago in your favorite application

So, the extension is this way: (This is a simple extension for getting the time before)

1extension Date {
2 func timeAgoDisplay() -> String {
3
4 let calendar = Calendar.current
5 let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
6 let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())!
7 let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())!
8 let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!
9
10 if minuteAgo < self {
11 let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0
12 return "\(diff) sec ago"
13 } else if hourAgo < self {
14 let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0
15 return "\(diff) min ago"
16 } else if dayAgo < self {
17 let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0
18 return "\(diff) hrs ago"
19 } else if weekAgo < self {
20 let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0
21 return "\(diff) days ago"
22 }
23 let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0
24 return "\(diff) weeks ago"
25 }
26 }

This class is very straightforward to use, here is an example:

1var now = Date()
2 now.timeAgoDisplay()

That’s it you can now display time ago in your chat application. I’ve made this post based on an stackoverflow answer that I wrote here

More articles from Julien Karst

How to mock a javascript module with jest

In this article we will see how to mock a module using jest. But first we will understand how to mock a module by overriding require cache which is what jest does.

December 15th, 2019 · 2 min read

How to setup circleci inside a monorepo

You might want to setup a ci for your monorepo. In this article we will see how to use Circleci inside a mono-repository. This post assume that you already have knowledge about monorepo and continuous integration process with Circleci.

November 19th, 2019 · 2 min read
© 2019–2020 Julien Karst
Link to $https://twitter.com/julienkarstLink to $https://github.com/JulienKodeLink to $https://instagram.com/julien.karstLink to $https://www.linkedin.com/in/julienkarst