获得当前系统时间毫秒的最佳方法是什么?


当前回答

这是我给斯威夫特用的

var date = NSDate()
let currentTime = Int64(date.timeIntervalSince1970 * 1000)

print("Time in milliseconds is \(currentTime)")

使用本网站验证准确性http://currentmillis.com/

其他回答

[[NSDate date] timeIntervalSince1970];

它以双精度返回自epoch以来的秒数。我几乎可以肯定你可以从小数部分访问毫秒。

我需要一个NSNumber对象,包含[[NSDate date] timeIntervalSince1970]的确切结果。因为这个函数被调用了很多次,我并不真的需要创建一个NSDate对象,性能不是很好。

所以要得到原始函数给我的格式,试试这个:

#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
double perciseTimeStamp = tv.tv_sec + tv.tv_usec * 0.000001;

这应该给你完全相同的结果[[NSDate date] timeIntervalSince1970]

斯威夫特2

let seconds = NSDate().timeIntervalSince1970
let milliseconds = seconds * 1000.0

斯威夫特3

let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
let timeInMiliSecDate = Date()
let timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)
print(timeInMiliSec)

这基本上和@TristanLorach发布的答案是一样的,只是为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)
   }