如何扩展Date/Calendar,让dateComponents结果可直接访问milliseconds属性?
解决方案:扩展DateComponents直接获取毫秒
当然可以实现,最直接的方式是给DateComponents添加一个计算属性,自动将纳秒转换为毫秒,这样你就能直接调用timeToEnd.milliseconds了。
扩展代码
extension DateComponents { var milliseconds: Int { // 安全处理纳秒的可选值,默认取0避免崩溃 (nanosecond ?? 0) / 1_000_000 } }
使用示例
现在你可以简化原来的代码,直接获取毫秒值:
let timeToEnd = Calendar.current.dateComponents( [.second, .nanosecond], from: .now, to: timerEnd ) // 直接调用milliseconds属性 return "\(timeToEnd.milliseconds)"
额外思路:通过Date扩展计算时间差毫秒
如果你想直接从两个Date计算毫秒差,也可以扩展Date,这种方式不需要依赖Calendar,适合单纯计算时间间隔的场景:
extension Date { func milliseconds(to date: Date) -> Int { let timeInterval = timeIntervalSince(date) return Int(abs(timeInterval) * 1000) } } // 使用方式 let millisecondsRemaining = Date().milliseconds(to: timerEnd) return "\(millisecondsRemaining)"
内容的提问来源于stack exchange,提问作者Joe Scotto
相关产品推荐
相关产品推荐

