How to get nsdate with millisecond accuracy?

前端 未结 3 1947
臣服心动
臣服心动 2020-12-11 00:26

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.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 01:05

    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.

提交回复
热议问题