强制本地化 DateComponentsFormatter 中的 allowedUnits

Force localization of the allowedUnits in DateComponentsFormatter

我有一个只有一种语言的应用程序。在显示自日期以来的时间间隔时,我想强制使用这种语言。例如。 “9 个月前”只是用一种特定的语言而不是英语。有没有一种方法可以使用 DateComponentsFormatter 来做到这一点,否则它完全符合我想对这些单位做的事情。

    func format(duration: TimeInterval) -> String {
        UserDefaults.standard.set(["da"], forKey: "AppleLanguages")
        UserDefaults.standard.synchronize()
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second]
        formatter.unitsStyle = .short
        formatter.includesApproximationPhrase = true
        formatter.maximumUnitCount = 1

        return formatter.string(from: -duration)!
    }

    format(duration: self.createdDate.timeIntervalSinceNow)

这个 returns 例如当语言为 en 时为“1 年”。 我想用特定的语言 ("yr" -> "år") 对其他允许的单位也应该这样做。

当 phone 设置为应用程序的语言时有效。

我尝试在创建 DateComponentsFormatter 之前设置语言,但它仍然以 phone 设置的语言返回。

EDIT 在下面插入了工作代码

根据答案修改后的工作代码:

    func format(duration: TimeInterval) -> String {
        var calendar = Calendar.current
        calendar.locale = Locale(identifier: "da")
        let formatter = DateComponentsFormatter()
        formatter.calendar = calendar
        formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second]
        formatter.unitsStyle = .short
        formatter.includesApproximationPhrase = true
        formatter.maximumUnitCount = 1

        return formatter.string(from: -duration)!
    }

    format(duration: self.createdDate.timeIntervalSinceNow)

这是默认的 iOS 行为。如果您在 phone 上更改区域设置和语言,您会注意到日历应用程序中可能有 2 种语言。有时可以更改语言环境,但您示例中的 includesApproximationPhrase 不会被翻译:

var calendar = Calendar.current
calendar.locale = Locale(identifier: "da")
let formatter = DateComponentsFormatter()
formatter.calendar = calendar