swiftuidateformatter

How to display Yesterday, Today, and Tomorrow with DateFormatter


Currently, I have been trying different ways of achieving this feat. The way I have formatted it here produces the current date Aug 30, 6:28 PM

import SwiftUI

struct TestDate: View {
    var time = Date()
    
    var dateFormatter: DateFormatter {
        let df = DateFormatter()
        df.dateFormat = "MMM d, h:mm a"
        return df
    }
    
    var body: some View {
        Text("\(time, formatter: dateFormatter)")
    }
}

This is exactly how I want it. HOWEVER, I want yesterday, today, and tomorrow to appear instead of "Aug 30"/the relative current date. How does one go about doing this in SwiftUI

Edit: What I meant was when I use a DatePicker and update the date. Instead of "Aug 29, 6:50 PM" to appear I would like the string to be "Yesterday, 6:50 PM". All dates exceeding yesterday and tomorrow would show as "MMM d, h:mm a"


Solution

  • You need doesRelativeDateFormatting (and don't forget to add styles), for eg:

    var dateFormatter: DateFormatter {
        let df = DateFormatter()
        df.dateFormat = "MMM d, h:mm a"
    
        df.dateStyle = .medium
        df.timeStyle = .short
        df.doesRelativeDateFormatting = true
    
        return df
    }