Whilst updating a project that I haven't looked at in a while I've been removing the various
Formatters in the project and replacing them with the newer
formatted() method which overall seems to have been fairly simple. However there's one case where I'm pretty stuck:
let formatter = DateFormatter() formatter.timeStyle = .short formatter.dateStyle = .short formatter.doesRelativeDateFormatting = true
I can get the equivalent style from
formatted for distant dates:
let myStyle = Date.FormatStyle(date: .numeric, time: .shortened).year(.twoDigits) let newYearsMidday = Calendar.current.date(from: DateComponents(year: 2023, month: 1, day: 1, hour: 12, minute: 0))! formatter.string(from: newYearsMidday) // "1/1/23, 12:00 PM" newYearsMidday.formatted(myStyle) // "1/1/23, 12:00 PM"
But I'm stumped about how to do it for closer dates that should use the relative date format:
formatter.string(from: .now) // "Today, 4:54 PM" Date.now.formatted(myStyle) // "2/12/23, 4:54 PM"
Is this possible with the new API or does it require sticking with