Formatting Dates in SwiftUI: A Beginner's Guide

"Format Date in SwiftUI" refers to the process of converting a date value into a more readable format that is easier to understand for the user. This involves customizing the way the date is displayed, such as the order of the day, month, and year, and the use of separators like dashes, slashes, or dots. 

In SwiftUI, there are several ways to format dates, including using the built-in date formatter or creating a custom date formatter with a specific format string. This allows developers to display dates in a way that is consistent with the design of their app and provides a better user experience for their users.

Transform how dates are displayed in your application by using a Date Extension and DateFormatter.

How do we format a date as [weekday], [month] [day], as in the image below?

DateFormatter 

Apple created a class called DateFormatter that facilitates the process of formatting dates. To get a date as a String and displayed as Tuesday, Dec 29, start by creating an extension for Date:

extension Date {

}

..

Then, create a function inside of that extension:

extension Date {
		func formatDate() -> String {
		    let dateFormatter = DateFormatter()
		    dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d")
		    return dateFormatter.string(from: self)
		}
}

..

In the code above, the important part is what you put in the parenthesis after .setLocalizedDateFormatFromTemplate. In our case, the EEEE represents the day of the week, MMM the first three letters of the month, and d is the date.

Then, in your View, simply call the getToday() extension on a Date :

let today = Date().formatDate()

..

And call the variable in a Text to display it:

Text(today)

..

Format a JavaScript string to a SwiftUI Date 

Let's say you got a string date after fetching data from Firestore or any other API in the yyyy-MM-dd'T'HH:mm:ss.SSSZ format (for example, 2021-02-01T09:45:00.000+02:00). 

To convert it to a SwiftUI Date, simply pass your string date in the function below:

func formatStringDate(date: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        let newDate = dateFormatter.date(from: date)
        dateFormatter.setLocalizedDateFormatFromTemplate("MMMM d, yyyy")
        return dateFormatter.string(from: newDate!)
}
// Output: February 1, 2021

..

Comments