DateIntervalFormatter's dateTemplate not consistent with DateFormatter's dateFormat in Swift

380 Views Asked by At

I am trying to display a date interval formatted using a custom format. The format which I am using works well for a date but do not so good when used with a date interval. I pus as comments what is displayed and what I expect. Is there truly a problem or my expectations are wrong, in case they are wrong, why so? also, how can I achieve the expected part?

import UIKit

let now = Date()
let tomorrow = now.addingTimeInterval(24.0 * 3600.0)
let dateInterval = DateInterval(start: now, end: tomorrow)

// Initialize Date Interval Formatter
let dateIntervalFormatter = DateIntervalFormatter()
dateIntervalFormatter.dateTemplate = "dd-MM-yyyy"

dateIntervalFormatter.locale = Locale(identifier: "de")
dateIntervalFormatter.string(from: dateInterval)
// displays "12.–13.01.2022"
// expected "12-–13-01-2022"

dateIntervalFormatter.locale = Locale(identifier: "en")
dateIntervalFormatter.string(from: dateInterval)
// displays "1/12/2022 – 1/13/2022"
// expected "12-01-2022 – 13-01-2022"

dateIntervalFormatter.locale = Locale(identifier: "ro")
dateIntervalFormatter.string(from: dateInterval)
// displays "12.01.2022 – 13.01.2022"
// expected "12-01-2022 – 13-01-2022"

let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
formatter.locale = Locale(identifier: "de")
let formatedTime = formatter.string(from: Date())
// displays "12-01-2022"
// expected "12-01-2022"
1

There are 1 best solutions below

1
matt On

A locale/template based format means "I yield the details to you", so the DateIntervalFormatter does what it pleases depending on the locale. The DateFormatter example, on the other hand, is not locale/template based, so you get what you specified in the format (not template) you supplied.