top of page
Writer's pictureHui Wang

7. SwiftUI: How to format the date in Text view


I'll describe here how to format the date content and display it in the text view.


Knowledge points:

  • First, add a date property to the current ContentView structure. The initial value of this date is the current date of the device.

var now = Date()

  • Next, add a date formatting type property to format the date content.

  • Initializes an instance of the date formatting type. Set the date formatting object's date style to long style, showing the day, month, and year values.

  • Finally, Return the instance formatter as the value of the date formatting property.

    static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()

  • Set the font style of the Text view to .title to increase the size of the text.

.font(.title)

  • Increase the spacing between text content and Text view borders.

.padding()

  • Then set the text content of the Text view and display the value of the date property according to the specified date format.

Text("The time is :\(now, formatter: Self.dateFormatter)")

After code:

struct ContentView: View {
    var now = Date()
    static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()
    
    var body: some View {
        Text("The time is :\(now, formatter: Self.dateFormatter)")
            .font(.title)
            .padding()
    }
}

Visual effects:


  • Finally, let's try to change the date format to full type, which will not only display the year, month, day, but also the day of the week.

formatter.dateStyle = .full


After code:

struct ContentView: View {
    var now = Date()
    static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .full
        return formatter
    }()
    
    var body: some View {
        Text("The time is :\(now, formatter: Self.dateFormatter)")
            .font(.title)
            .padding()
    }
}

Visual effects:


 

Follow me on:

ความคิดเห็น


bottom of page