How to format date in SwiftUI


Greetings, traveler!

Displaying dates in SwiftUI has become remarkably straightforward, reducing reliance on DateFormatter for basic date display. This API will use the current locale, so examples can produce different results.

So, let’s check out the code.

import SwiftUI

struct ContentView: View {
        
    var body: some View {
        // 10.12.2024, 20:54
        Text(Date.now.formatted())
        
        // 10.12.2024
        Text(Date.now.formatted(date: .numeric, time: .omitted))
        
        // 20:54:42
        Text(Date.now.formatted(date: .omitted, time: .standard))
        
        // 2024-12-10T16:33Z
        Text(Date.now.formatted(.iso8601))
        
        // 10 Dec, 2024 at 20:54:42 GMT+4
        Text(Date.now.formatted(date: .abbreviated, time: .complete))
        
        // 10 December 2024
        Text(Date.now.formatted(date: .long, time: .omitted))
        
        // 10
        Text(Date.now, format: Date.FormatStyle().day())
        
        // 10 Dec
        Text(Date.now, format: Date.FormatStyle().day().month())
        
        // 10 Dec, 2024
        Text(Date.now, format: Date.FormatStyle().day().month().year())
        
        // 10.12.2024
        Text(Date.now, format: Date.FormatStyle().day().month(.twoDigits).year())
    }
    
}