DateIntervalFormatter 的 dateTemplate 与 Swift 中的 DateFormatter 的 dateFormat 不一致



我正在尝试显示使用自定义格式格式化的日期间隔。我使用的格式适用于日期,但与日期间隔一起使用时就不那么好了。我把展示的内容和我的期望作为评论。真的有问题吗?或者我的期望是错误的,如果是错误的话,为什么会这样?此外,我如何才能达到预期的部分?

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"

基于区域设置/模板的格式意味着"我把细节交给你";,因此DateIntervalFormatter根据区域设置执行它喜欢的操作。另一方面,DateFormatter示例不是基于区域设置/模板的,因此您可以在提供的格式(而不是模板(中获得指定的内容。

最新更新