没有得到两个日期之间的毫秒差异

问题描述 投票:1回答:1

在我的应用程序中,我需要某种计时器,如倒计时。与下一场比赛一样,有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"]

我需要几毫秒。

swift nscalendar
1个回答
0
投票

您不能使用DateComponentsFormatter格式化毫秒。根据documentation,只允许这些日历单位:

  • 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))
© www.soinside.com 2019 - 2024. All rights reserved.