我不是iOS开发人员,但是开始学习Swift。
我尝试将一些逻辑从Android项目转换为iOS
我有以下方法:
func addGroupItemSample(sample : WmGroupItemSample){ // some custom class
var seconds: NSTimeInterval = NSDate().timeIntervalSince1970
var cuttDate:Double = seconds*1000;
var sampleDate: UInt64 = sample.getStartDate(); // <-- problematic place
if(sampleDate > cuttDate){
// ....
}
}
从上面的方法中,您可以看到sample.getStartDate()
返回类型UInt64
。
我认为它与Java中的long
相似:System.currentTimeMillis()
但当前时间(以毫秒为单位)定义为Double
。
混合Double
和UInt64
是否合适?或者我只需将所有毫秒表示为Double
?
谢谢,
答案 0 :(得分:28)
func currentTimeMillis() -> Int64{
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble*1000)
}
答案 1 :(得分:5)
Swift不允许比较不同的类型。
seconds
是一个Double
浮点值,以秒为单位,精确度为亚秒级
sampleDate
是一个UInt64,但没有给出单位。
sampleDate
需要转换为Double
浮点值,单位为秒。
var sampleDate: Double = Double(sample.getStartDate())
然后可以比较它们:
if(sampleDate > cuttDate){}
答案 2 :(得分:4)
这是Swift 3的替代版本:
/// Method to get Unix-style time (Java variant), i.e., time since 1970 in milliseconds. This
/// copied from here: http://stackoverflow.com/a/24655601/253938 and here:
/// http://stackoverflow.com/a/7885923/253938
/// (This should give good performance according to this:
/// http://stackoverflow.com/a/12020300/253938 )
///
/// Note that it is possible that multiple calls to this method and computing the difference may
/// occasionally give problematic results, like an apparently negative interval or a major jump
/// forward in time. This is because system time occasionally gets updated due to synchronization
/// with a time source on the network (maybe "leap second"), or user setting the clock.
public static func currentTimeMillis() -> Int64 {
var darwinTime : timeval = timeval(tv_sec: 0, tv_usec: 0)
gettimeofday(&darwinTime, nil)
return (Int64(darwinTime.tv_sec) * 1000) + Int64(darwinTime.tv_usec / 1000)
}
答案 3 :(得分:1)
func get_microtime() -> Int64{
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble*1000)
}
工作正常
答案 4 :(得分:0)
UInt64 中获取时间令牌的简单一行代码
让时间 = UInt64(Date().timeIntervalSince1970 * 1000)
print(time) <----- 在 UInt64 中打印时间
额外提示:
为 API 调用寻找 自 1970 年以来 10 位毫秒的时间戳
让 timeStamp = Date().timeIntervalSince1970
print(timeStamp) <-- 打印当前时间戳