获得当前系统时间毫秒的最佳方法是什么?
当前回答
func currentmicrotimeTimeMillis() -> Int64{
let nowDoublevaluseis = NSDate().timeIntervalSince1970
return Int64(nowDoublevaluseis*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)
}
获取当前日期的毫秒数。
斯威夫特4 +:
func currentTimeInMilliSeconds()-> Int
{
let currentDate = Date()
let since1970 = currentDate.timeIntervalSince1970
return Int(since1970 * 1000)
}
CFAbsoluteTimeGetCurrent ()
Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.
试试这个:
NSDate * timestamp = [NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSS"];
NSString *newDateString = [dateFormatter stringFromDate:timestamp];
timestamp = (NSDate*)newDateString;
在本例中,dateWithTimeIntervalSince1970与格式化程序@"YYYY-MM-dd HH:mm:ss结合使用。它将返回带有年、月、日的日期和带有小时、分钟、秒和毫秒的时间。参见示例:"2015-12-02 04:43:15.008"。我使用NSString来确保格式之前已经写过。
[[NSDate date] timeIntervalSince1970];
它以双精度返回自epoch以来的秒数。我几乎可以肯定你可以从小数部分访问毫秒。
推荐文章
- 我如何获得iOS 7默认的蓝色编程?
- UITapGestureRecognizer破坏UITableView didSelectRowAtIndexPath
- 在Objective-C中@property保留,赋值,复制,非原子
- 6.5英寸屏幕的App store截图大小是多少?
- 我如何在NSAttributedString中创建一个可点击的链接?
- iOS测试/规格TDD/BDD以及集成和验收测试
- 停止UIWebView垂直“弹跳”?
- 启动屏幕故事板不显示图像
- 是否可以为iPhone应用程序(如YouTube和地图)注册一个基于http+域的URL方案?
- 模拟器错误fbssystemservicdomain代码4
- 改变UISegmentedControl的字体大小
- 我可以强制UITableView隐藏分隔符之间的空单元格吗?
- 获取用户当前位置/坐标
- 获得推送通知,而应用程序在前台iOS
- 如何取消选定的UITableView单元格?