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.
Asked
Active
Viewed 3.1k times
24

Cœur
- 37,241
- 25
- 195
- 267

sujith1406
- 2,822
- 6
- 40
- 60
3 Answers
30
You'll need to use the below method to convert sec. into millisecond:
([NSDate timeIntervalSinceReferenceDate] * 1000)

Kees C. Bakker
- 32,294
- 27
- 115
- 203

Jhaliya - Praveen Sharma
- 31,697
- 9
- 72
- 76
-
1For more you can go through the already discussed post http://stackoverflow.com/questions/889380/how-can-i-get-a-precise-time-for-example-in-milliseconds-in-objective-c – Jhaliya - Praveen Sharma Mar 19 '11 at 04:24
-
5This does nothing to improve the ACCURACY of this date. All you are doing is taking the value and converting it to be in units of milliseconds. If the level of precision was 100 ms before, its 100 ms after. So be careful - this answer is deceptive. – bkbeachlabs Feb 20 '18 at 20:04
-
Please read the problem description carefully before commenting, the user wanted to convert to the millisecond and had accepted the answer. – Jhaliya - Praveen Sharma Feb 22 '18 at 05:56
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.

steviesama
- 337
- 4
- 13
4
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)

Thorsten Niehues
- 13,712
- 22
- 78
- 113
-
3All you're doing is taking a seconds-accurate figure and multiplying it by 1000. That doesn't address the question. (Besides, somebody posted the same useless response three years earlier, right up above!) – Ben Kennedy Aug 21 '20 at 18:08