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


当前回答

在Swift中,我们可以创建一个函数,并如下所示

func getCurrentMillis()->Int64{
    return  Int64(NSDate().timeIntervalSince1970 * 1000)
}

var currentTime = getCurrentMillis()

虽然它在Swift 3.0中工作得很好,但我们可以修改和使用Date类而不是3.0中的NSDate

斯威夫特3.0

func getCurrentMillis()->Int64 {
    return Int64(Date().timeIntervalSince1970 * 1000)
}

var currentTime = getCurrentMillis()

其他回答

[[NSDate date] timeIntervalSince1970];

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

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];

斯威夫特2

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

斯威夫特3

let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds

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/

试试这个:

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来确保格式之前已经写过。