ioskayn ioskayn - 5 months ago 24
Objective-C Question

Convert time to local time in Objective-C

I'm having this issue where the correct time is passed but once it hits the

[formatter setDateFormat:date]
it comes out in a different time zone. Here is a snippet

NSDate* date = user.startDate;
NSDateFormatter *format = [[NSDateFormatter alloc] init];
NSLog(@"-------> (1) time is %@", date);
NSLog(@"-------> (2) time is %@", date);
[format setDateFormat:@"h:mm a"];
NSLog(@"-------> (3) time is %@", date);
NSLog(@"-------> (4) time is %@", [format stringFromDate:date]);


Here is the debugger output for the log messages

-------> (1) time is 2016-06-30 09:25:17 +0000
-------> (2) time is 2016-06-30 09:25:17 +0000
-------> (3) time is 2016-06-30 09:25:17 +0000
-------> (4) time is 2:25 AM


I'm expecting the output for
(4)
to be
time is 9:25 AM

Answer

Your time zone is apparently UTC-7000.

NSLog prints NSDate objects always in UTC, NSDateFormatter considers the current time zone. The printed dates are actually the same.

If you really need all dates in UTC, set the time zone of the formatter.

format.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

By the way: There are built-in methods to check if a date is in today or yesterday.

Comments