在我的应用程序中,我需要某种计时器,如倒计时。与下一场比赛一样,有1年2个月6天23分24秒,剩下5毫秒。
为此,我使用此代码:
extension DateComponentsFormatter {
func difference(from fromDate: Date, to toDate: Date) -> String? {
self.allowedUnits = [.year,.month,.day,.hour, .minute, .second ,.nanosecond]
self.maximumUnitCount = 8
self.unitsStyle = .full
return self.string(from: fromDate, to: toDate)
}
}
但我没有得到毫秒。
这是我得到的:
["24 years", " 8 months", " 20 days", " 12 hours", " 2 minutes", " 48 seconds"]
我需要几毫秒。
答案 0 :(得分:0)
您不能使用DateComponentsFormatter
格式化毫秒。根据{{3}},只允许使用这些日历单元:
year
month
weekOfMonth
day
hour
minute
second
您必须自己设置格式,方法是在日期之间获取TimeInterval
,获取时间间隔的小数部分,然后格式化。
以下是对此的看法。
extension DateComponentsFormatter {
func difference(from fromDate: Date, to toDate: Date) -> String? {
self.allowedUnits = [NSCalendar.Unit.second]
allowsFractionalUnits = true
self.maximumUnitCount = 8
self.unitsStyle = .full
guard let firstPart = self.string(from: fromDate, to: toDate) else { return nil }
let milliseconds = abs(toDate.timeIntervalSince(fromDate)).remainder(dividingBy: 1) * 1000
let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = 0
guard let secondPart = numberFormatter.string(from: milliseconds as NSNumber) else { return nil }
return "\(firstPart) \(secondPart) milliseconds"
}
}
let formatter = DateComponentsFormatter()
formatter.difference(from: Date(), to: Date().addingTimeInterval(0.5))