Swift ios日期为毫秒Double或UInt64?

时间:2014-08-12 11:24:55

标签: swift nsdate nstimeinterval

我不是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

混合DoubleUInt64是否合适?或者我只需将所有毫秒表示为Double

谢谢,

5 个答案:

答案 0 :(得分:28)

在iOS中,最好使用double,但是如果你想轻松移植代码并保持一致,你可以试试这个:

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) <-- 打印当前时间戳