获得当前系统时间毫秒的最佳方法是什么?
当前回答
// Timestamp after converting to milliseconds.
NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
其他回答
斯威夫特2
let seconds = NSDate().timeIntervalSince1970
let milliseconds = seconds * 1000.0
斯威夫特3
let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds
NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); //double
long digits = (long)time; //first 10 digits
int decimalDigits = (int)(fmod(time, 1) * 1000); //3 missing digits
/*** long ***/
long timestamp = (digits * 1000) + decimalDigits;
/*** string ***/
NSString *timestampString = [NSString stringWithFormat:@"%ld%03d",digits ,decimalDigits];
如果你不想包含Quartz框架,[NSDate timeintervalsincerely eferencedate]是另一个选项。它返回一个double,表示秒数。
It may be useful to know about CodeTimestamps, which provide a wrapper around mach-based timing functions. This gives you nanosecond-resolution timing data - 1000000x more precise than milliseconds. Yes, a million times more precise. (The prefixes are milli, micro, nano, each 1000x more precise than the last.) Even if you don't need CodeTimestamps, check out the code (it's open source) to see how they use mach to get the timing data. This would be useful when you need more precision and want a faster method call than the NSDate approach.
http://eng.pulse.me/line-by-line-speed-analysis-for-ios-apps/
如果你正在考虑使用这个相对定时(例如游戏或动画),我宁愿使用CACurrentMediaTime()
double CurrentTime = CACurrentMediaTime();
哪一种是推荐的方式;NSDate从网络的同步时钟中提取,并且在与网络重新同步时偶尔会打嗝。
它返回当前的绝对时间,以秒为单位。
如果你只想要小数部分(通常在同步动画时使用),
let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
推荐文章
- 前一个月的Python日期
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- Xcode 4 -在新的Macintosh安装上的配置文件上“没有找到有效的签名标识”错误
- 在iPhone上确定用户是否启用了推送通知
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 错误ITMS-9000:“冗余二进制文件上传。火车1.0版本已经有一个二进制版本上传。
- Swift -转换为绝对值
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容
- 在代码中为UIButton设置一个图像
- NSRange从Swift Range?
- UICollectionView中的单元格间距
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?