获得当前系统时间毫秒的最佳方法是什么?
当前回答
到目前为止,我发现gettimeofday在iOS (iPad)上是一个很好的解决方案,当你想执行一些间隔评估(比如帧速率,渲染帧的计时……):
#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);
其他回答
这基本上和@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)
}
斯威夫特2
let seconds = NSDate().timeIntervalSince1970
let milliseconds = seconds * 1000.0
斯威夫特3
let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
如果你不想包含Quartz框架,[NSDate timeintervalsincerely eferencedate]是另一个选项。它返回一个double,表示秒数。
如果你正在考虑使用这个相对定时(例如游戏或动画),我宁愿使用CACurrentMediaTime()
double CurrentTime = CACurrentMediaTime();
哪一种是推荐的方式;NSDate从网络的同步时钟中提取,并且在与网络重新同步时偶尔会打嗝。
它返回当前的绝对时间,以秒为单位。
如果你只想要小数部分(通常在同步动画时使用),
let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
这是我给斯威夫特用的
var date = NSDate()
let currentTime = Int64(date.timeIntervalSince1970 * 1000)
print("Time in milliseconds is \(currentTime)")
使用本网站验证准确性http://currentmillis.com/
推荐文章
- 如何在c#中获得正确的时间戳
- 保留HTML字体大小时,iPhone的方向从纵向改变为横向
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示