Reputation: 15
How get the time when i call NSLog in format string and further to use this time? I need time to microseconds?
2017-09-28 20:19:39.383263+0300 NIR[5677:1383138] а
Upvotes: 1
Views: 262
Reputation: 6090
Here's a method you can use. It returns an (NSString *) with the current timestamp. It's a little messy because there's not a formatter string to get the seconds including milliseconds:
- (NSString*)dateTimeWithMS
{
CFAbsoluteTime timeInSeconds = CFAbsoluteTimeGetCurrent();
NSDate *d = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInSeconds];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"yyyy-MM-dd H:mm:ss";
NSString *s = [df stringFromDate:d];
int ms = (int) round(1000 * (timeInSeconds - floor(timeInSeconds)));
NSString *result = [NSString stringWithFormat:@"%@\.%000d", s, ms];
return(result);
}
Basically we get the time, use the standard formatting, and then append the milliseconds.
You can test it with this:
for(int i = 0; i < 10; ++i)
NSLog(@"Time #%d with MS = %@", i, [self dateTimeWithMS]);
You will get output something like this -- you can see Xcode's timestamp matches ours:
2017-09-28 18:28:10.781 TimeMillisecondTest[2497:463749] Time #0 with MS = 2017-09-28 18:28:10.780
2017-09-28 18:28:10.781 TimeMillisecondTest[2497:463749] Time #1 with MS = 2017-09-28 18:28:10.781
2017-09-28 18:28:10.781 TimeMillisecondTest[2497:463749] Time #2 with MS = 2017-09-28 18:28:10.782
2017-09-28 18:28:10.781 TimeMillisecondTest[2497:463749] Time #3 with MS = 2017-09-28 18:28:10.782
2017-09-28 18:28:10.782 TimeMillisecondTest[2497:463749] Time #4 with MS = 2017-09-28 18:28:10.782
2017-09-28 18:28:10.782 TimeMillisecondTest[2497:463749] Time #5 with MS = 2017-09-28 18:28:10.782
2017-09-28 18:28:10.782 TimeMillisecondTest[2497:463749] Time #6 with MS = 2017-09-28 18:28:10.782
2017-09-28 18:28:10.782 TimeMillisecondTest[2497:463749] Time #7 with MS = 2017-09-28 18:28:10.783
2017-09-28 18:28:10.782 TimeMillisecondTest[2497:463749] Time #8 with MS = 2017-09-28 18:28:10.783
2017-09-28 18:28:10.783 TimeMillisecondTest[2497:463749] Time #9 with MS = 2017-09-28 18:28:10.783
Upvotes: 1