Home > Software engineering >  How to format String to use Today and Yesterday instead of Date if appropriate in Swift?
How to format String to use Today and Yesterday instead of Date if appropriate in Swift?

Time:10-19

Context

I have a custom Stringify Method on Date formatting a given Date into a String. The result looks like this:

October 17th, 2022 at 1:27pm

However, when the Date is Today, Yesterday or Tomorrow, I would like to replace the actual Date with this specific String description. The result should look like this:

Today at 1:27pm


Code

extension Date {
    func stringify() -> String {
        let dateFormatter = DateFormatter()
        
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .short
        
        return dateFormatter.string(from: self)
    }
}

Question

  • How can I achieve this behaviour, since DateFormatter is not supporting it?

CodePudding user response:

As suggested in the comments, you can use DateFormatter for this, the trick is to turn on the doesRelativeDateFormatting flag.

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)!

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
dateFormatter.doesRelativeDateFormatting = true

let todayString = dateFormatter.string(from: today)
print(todayString) // Today at 20:44

let yesterdayString = dateFormatter.string(from: yesterday)
print(yesterdayString) // Yesterday at 20:44

let tomorrowString = dateFormatter.string(from: tomorrow)
print(tomorrowString) // Tomorrow at 20:44
  • Related