How to get nsdate with millisecond accuracy?

孤街浪徒 提交于 2019-11-28 11:55:20
Jhaliya

You'll need to use the below method to convert sec. into millisecond:

([NSDate timeIntervalSinceReferenceDate] * 1000)

For those who want to get the time in mili seconds (like in Java)

double timestamp = [[NSDate date] timeIntervalSince1970];
int64_t timeInMilisInt64 = (int64_t)(timestamp*1000);

(tested with iOS7 and the iPhone simulator using Xcode 5)

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:

/*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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!