PaulLian
PaulLian

Reputation: 307

How to get the millisecond part of current time?

I'm trying to record an event at its happening time by accuracy of milliseconds. Below is my code:

        NSDate * now = [NSDate date];
        NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
        [outputFormatter setDateFormat:@"HH:mm:ss.SSS"];
        NSString *timeString = [outputFormatter stringFromDate:now];

However, the results are as this:

45:11.3

It looks like time record has been rounded to 0.1 second, while all the second and third decimal accuracy is lost. Can anyone suggest where the problem is and how I can get the millisecond information?

Thank you all!

Paul

Upvotes: 0

Views: 58

Answers (1)

matt
matt

Reputation: 535305

Your code works fine for me. Here it is (in Swift):

let f = NSDateFormatter()
f.dateFormat = "HH:mm:ss.SSS"
let timeString = f.stringFromDate(NSDate()) // "20:26:19.118"

You do not show the code by which you read the resulting timeString but perhaps the fault lies in how you are doing that. It is odd that the Hour part is missing from your output too.

Upvotes: 2

Related Questions