场合
我有一个函数使用DateComponentFormatter
的函数fun string(from: Date, to: Date)
根据两个日期之间的时间差返回格式化的字符串,并且它完美地运行。但是我想以英文返回这个格式化的字符串(目前根据设备本地格式化)。
问题
如何设置DateComponentFormatter
本地内容,就像使用DateFormatter
一样?如果你不能,你将如何进行?
代码:
import Foundation
func returnRemainingTimeAsString(currentDate: Date, nextDate: Date)->String {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
dateComponentsFormatter.allowedUnits = [.day, .hour, .minute, .second]
dateComponentsFormatter.maximumUnitCount = 1
let differenceAsString = dateComponentsFormatter.string(from: currentDate, to: nextDate)!
return differenceAsString
}
let currentDate = Date()
let futureDate = currentDate.addingTimeInterval(3604)
returnRemainingTimeAsString(currentDate: currentDate, nextDate: futureDate)
// prints 1 hour (if devices local is English) or 1 hora (if Spanish),
// and I want it to return always 1 hour.
答案 0 :(得分:2)
DateComponentsFormatter
具有calendar
属性。
获取当前日历,设置其区域设置并将日历分配给格式化程序。
let dateComponentsFormatter = DateComponentsFormatter()
var calendar = Calendar.current
calendar.locale = Locale(identifier: "en_US_POSIX")
dateComponentsFormatter.calendar = calendar
dateComponentsFormatter.unitsStyle = .full
...
答案 1 :(得分:0)