在我的应用程序中,我需要某种计时器,例如倒计时。与下一场比赛一样,还有 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"]
我需要毫秒。
最佳答案
您不能使用 DateComponentsFormatter
来格式化毫秒。根据documentation , 只允许这些日历单位:
年份
月份
weekOfMonth
天
小时
分钟
第二个
您必须自己设置格式,方法是获取日期之间的 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))
关于swift - 两个日期之间没有毫秒差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186527/