Swift ios日期为毫秒Double或UInt64?

sna*_*ggs 16 nsdate nstimeinterval swift

我不是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){
   // ....
  }
}
Run Code Online (Sandbox Code Playgroud)

从上面的方法,您可以看到sample.getStartDate()返回类型UInt64.

我认为它long在Java中是这样的:System.currentTimeMillis()

但当前时间以毫秒为单位定义为Double.

是混合的正确方法Double,UInt64还是我只需要代表所有毫秒Double

谢谢,

Ben*_*Ben 28

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

func currentTimeMillis() -> Int64{
    let nowDouble = NSDate().timeIntervalSince1970
    return Int64(nowDouble*1000)
}
Run Code Online (Sandbox Code Playgroud)

  • 变量'nowDouble'从未发生变异; 考虑改为'let'常数 (3认同)

Ren*_*Pet 6

这是 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)
   }
Run Code Online (Sandbox Code Playgroud)


zap*_*aph 5

Swift不允许比较不同的类型.

seconds是以Double秒为单位的浮点值,具有亚秒级精度.
sampleDate是一个UInt64但没有给出单位. sampleDate需要转换为Double浮点值,单位为秒.

var sampleDate: Double = Double(sample.getStartDate())
Run Code Online (Sandbox Code Playgroud)

然后他们可以比较:

if(sampleDate > cuttDate){}
Run Code Online (Sandbox Code Playgroud)