ios 如何以毫秒精度获取nsdate?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5359977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get nsdate with millisecond accuracy?
提问by sujith1406
I need to get time in millisecond accuracy. How can I get it from NSDate
. Currently when I NSLog
time, it is showing only upto seconds.
我需要获得毫秒精度的时间。我怎样才能从NSDate
. 目前,当我NSLog
计时时,它最多只显示几秒钟。
回答by Jhaliya
You'll need to use the below method to convert sec. into millisecond:
您需要使用以下方法转换秒。成毫秒:
([NSDate timeIntervalSinceReferenceDate] * 1000)
回答by Thorsten Niehues
For those who want to get the time in mili seconds (like in Java)
对于那些谁想要得到的时间毫秒(象Java)
double timestamp = [[NSDate date] timeIntervalSince1970];
int64_t timeInMilisInt64 = (int64_t)(timestamp*1000);
(tested with iOS7 and the iPhone simulator using Xcode 5)
(使用 Xcode 5 使用 iOS7 和 iPhone 模拟器测试)
回答by steviesama
Kees is right about the milliseconds calculation, but you might want to consider processing only the fractional part of the time interval as you can use NSDateComponents to get all the time components down to the second. If you use something like the following, you can add a milliseconds component to that:
Kees 关于毫秒计算是正确的,但您可能需要考虑仅处理时间间隔的小数部分,因为您可以使用 NSDateComponents 将所有时间分量降到秒。如果您使用类似以下内容,则可以向其添加毫秒组件:
/*This will get the time interval between the 2
dates in seconds as a double/NSTimeInterval.*/
double seconds = [date1 timeIntervalSinceDate:date2];
/*This will drop the whole part and give you the
fractional part which you can multiply by 1000 and
cast to an integer to get a whole milliseconds
representation.*/
double milliSecondsPartOfCurrentSecond = seconds - (int)seconds;
/*This will give you the number of milliseconds accumulated
so far before the next elapsed second.*/
int wholeMilliSeconds = (int)(milliSecondsPartOfCurrentSecond * 1000.0);
Hope that was helpful.
希望这是有帮助的。