我需要找到两个Unix epoch time
之间的区别。
let currentTime = Date().timeIntervalSince1970
let comingFromTheServer = TimeInterval(1552078800000)
如何找到两次之间的分钟数差异?两者都是本地时区的Epoch time
let currentTime = Date().timeIntervalSince1970 // printing 25842307795.623497 which is somewhere in january
let startedTinme = TimeInterval(1552090800000 / 1000)
print((currentTime - startedTinme) / 60)
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second]
formatter.unitsStyle = .abbreviated
let formatted = formatter.string(for: currentTime - startedTinme)
print(formatted)
我猜是发生了一些误解。我想找出current time
与specific
时间之间的时差。我尝试了(更新)版本的代码:
我正在使用此扩展程序以毫秒为单位(当前时间)获取当前时间
extension Date {
var millisecondsSince1970:Int {
return Int((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds:Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
我正在从服务器接收时间,即1552086180000
,即5:03 PM
我当前的时间是5:12 PM
。因此,差异应该为9 Minutes
。为此,我正在使用
let currentTime = Date().millisecondsSince1970
let startedTinme = TimeInterval(1552086180000) / 1000
How can I get the difference of `9` minutes here ?
答案 0 :(得分:0)
首先,您必须将来自服务器的时间正确地转换为TimeInterval
。 Unix时间通常以毫秒为单位,而TimeInterval
以秒为单位,因此:
let currentTime = Date().timeIntervalSince1970
let comingFromTheServer = TimeInterval(1552078800000) / 1000
然后只计算差异并转换为分钟:
print((currentTime - comingFromTheServer) / 60) // 160
或格式化:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second]
formatter.unitsStyle = .abbreviated
let formatted = formatter.string(from: currentTime - comingFromTheServer) ?? ""
print(formatted) // 160m 41s
考虑您的millisecondsSince1970
函数,只需将其转换回秒:
let currentTime = TimeInterval(Date().millisecondsSince1970) / 1000
let startedTime = TimeInterval(1552086180000) / 1000