Learning Date&Time FormatStyle

Date.FormatStyle

I'm constantly trying to understand the many ways to format or parse Date and Time in Swift. Back in 2021, Swift 5.5 Apple included another "simpler" method. Let's explore that now.

I'm using the Xcode Playground to experiment. I've crafted a Date extension to separate concerns and make the call-site clean and explicit.

Notice the comma in the last line of printout - caused by adding the year() method.

Here's the Date Extension:


import Foundation


var greeting = "Hello, playground"




extension Date {

var displayFormat: String {

self.formatted( .dateTime

.year()

.month()

.day()

)

}

var YearOnly_dateFormat: String {

self.formatted(.dateTime.year())

}

var YearOnlyTwoDigits_dateFormat: String {

self.formatted(.dateTime.year(.twoDigits))

}

var WideMonthAndYear_dateFormat: String {

self.formatted(.dateTime

.year()

.month(.wide)

)

}

var JSON_dateTimeFormat: String {

self.formatted(.iso8601)

}

var MDY_dateFormat: String {

self.formatted(date: .numeric, time: .omitted)

} // this format MDY is because of Locale not this format.

var WeekDayOnly_dateTimeFormat: String {

self.formatted(Date.FormatStyle().weekday(.abbreviated))

}

var LocaleGB_dateTimeFormat: String {

self.formatted(.dateTime

.day(.twoDigits)

.month(.wide)

//.year()

.weekday(.abbreviated)

.hour(.conversationalTwoDigits(amPM: .wide))

.locale(Locale(identifier: "en_GB"))

)

}

var LocaleGBWithYear_dateTimeFormat: String {

self.formatted(.dateTime

.day(.twoDigits)

.month(.wide)

.year()

.weekday(.abbreviated)

.hour(.conversationalTwoDigits(amPM: .wide))

.locale(Locale(identifier: "en_GB"))

)

}

}





print( Date().displayFormat )

print( Date().MDY_dateFormat )

print( Date().YearOnly_dateFormat )

print( Date().YearOnlyTwoDigits_dateFormat )

print( Date().WideMonthAndYear_dateFormat )

print( Date().JSON_dateTimeFormat )

print( Date().WeekDayOnly_dateTimeFormat )

print( Date().LocaleGB_dateTimeFormat )

print( Date().LocaleGBWithYear_dateTimeFormat )




2022-11-07

I've still not worked out the incantation to produce a common (and logically consistent) date format needed by the News API I'm trying to call. It would be YYYY-MM-DD with dashes, not slashes, and time omitted. The Locale of "enUS" gives dates with slashes and the stupid MM/DD/YYYY style (logically incongruent).

Locale - a hard document to find with some interesting details.

Well - wouldn't you know ... it would be in the last place I looked! So it was not a trick of Locale that made it work. It was the iso8601 style with the dateSeperator(.dash).....

Now I've got a YMD_Format.