sta*_*set 4 nsdate swift nsdatecomponentsformatter
情况
我有一个函数,它使用DateComponentFormatter's 函数fun string(from: Date, to: Date)根据两个日期之间的时差返回一个格式化的字符串,它工作得很好。但是我想始终以英语返回这个格式化的字符串(当前根据设备的本地格式进行格式化)。
问题
你如何DateComponentFormatter像你可以用DateFormatter's做的那样设置's 本地?如果你不能,你将如何进行?
代码:
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.
Run Code Online (Sandbox Code Playgroud)
DateComponentsFormatter有一个calendar属性。
获取当前日历,设置其语言环境并将日历分配给格式化程序。
let dateComponentsFormatter = DateComponentsFormatter()
var calendar = Calendar.current
calendar.locale = Locale(identifier: "en_US_POSIX")
dateComponentsFormatter.calendar = calendar
dateComponentsFormatter.unitsStyle = .full
...
Run Code Online (Sandbox Code Playgroud)