如何获得具有毫秒精度的nsdate?

suj*_*406 20 nsdate ios

我需要以毫秒精度获得时间.我怎么能得到它NSDate.目前,当我的NSLog时间,它只显示秒.

Jha*_*iya 29

您需要使用以下方法转换秒.毫秒:

([NSDate timeIntervalSinceReferenceDate] * 1000)
Run Code Online (Sandbox Code Playgroud)

  • 这无助于提高此日期的准确性.您所做的就是获取值并将其转换为以毫秒为单位.如果精度水平在100毫秒之前,则在100毫秒之后.所以要小心 - 这个答案具有欺骗性. (3认同)

Tho*_*ues 6

对于那些想要以毫秒计算时间的人(比如Java)

double timestamp = [[NSDate date] timeIntervalSince1970];
int64_t timeInMilisInt64 = (int64_t)(timestamp*1000);
Run Code Online (Sandbox Code Playgroud)

(使用Xcode 5测试iOS7和iPhone模拟器)

  • 您所做的就是获取精确到秒的数字并将其乘以 1000。这并不能解决问题。(此外,有人在三年前发布了同样无用的回复,就在上面!) (2认同)

ste*_*ama 5

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);
Run Code Online (Sandbox Code Playgroud)

希望这有帮助。