Creating Relative Date and Time Formatter in Swift (e.g: in 1 day ago, 5 minutes ago, in 2 hours go, etc)
In iOS 13.0 and above, we have access to a new date formatter class called RelativeDateTimeFormatter
that allows us to format dates in a relative way. This means that we can display dates like “5 minutes ago,” “in 1 day,” “last week,” and so on.
To use this formatter class, we can create a custom Date
extension that makes it easier to use. In the following example, we’ll create an extension that returns a relative time string based on the current date:
extension Date {
func formatRelativeTime() -> String {
let date = self
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let string = formatter.localizedString(for: date, relativeTo: Date())
return string
}
}
Here, we create a RelativeDateTimeFormatter
object and set its units style to .full
. This means that the formatter will use full names for units of time, such as “5 minutes ago” instead of “5 min ago.” We then use the formatter to get the relative time string for the given date.
Now, let’s see how we can use this extension to format dates:
import Foundation
// MARK: Extension
extension Date {
func formatRelativeTime() -> String {
let date = self
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let string = formatter.localizedString(for: date, relativeTo: Date())
return string
}
}
// MARK: Create a sample date
let string = "01/02/2016"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yy"
let date = dateFormatter.date(from: string)
if let date = date {
// MARK: Use the extension
print(date.formatRelativeTime())
}
In this example, we first import the Foundation
framework to use the Date
class. We then create a sample date using the DateFormatter
class, which takes a string and a format string to create a Date
object. We then use the formatRelativeTime()
method of our custom Date
extension to get the relative time string for the date.
When we run this code, we get the output ”7 years ago”, which is the relative time string for the sample date we created.
The nice thing about this extension is that we can use it with any Date
object. For example, we could use it to format the current date:
let now = Date()
print(now.formatRelativeTime()) // e.g: 5 minutes ago
Or we could use it to format a date that’s in the future:
let futureDate = Date().addingTimeInterval(60 * 60 * 24 * 7) // 1 week from now
print(futureDate.formatRelativeTime()) // e.g: in 6 days
In summary, using RelativeDateTimeFormatter
and a custom Date
extension makes formatting relative date and time strings in Swift simple and elegant.