I have configured my phone (actual device, not simulator) to be in London UK which is GMT.
When I set the timezone on a NSCalendar
using localTimeZone
, it gives me the time off by 1 minute and 15 seconds as compared to if I set it using [NSTimeZone timeZoneWithAbbreviation:@"GMT"]
. Shouldn't both be giving me the same result if my timezone is already set to GMT?
Another thing I notice is that if I set break points, the NSDate
created using localTimeZone
inspected via the breakpoint is off by 1 minute and 15 seconds but the NSLog prints the correct time (Breakpoint shows: 0000-12-30 09:01:15 UTC but NSLog prints Sat Dec 30 09:00:00 0000):
But when I use [NSTimeZone timeZoneWithAbbreviation:@"GMT"]
, then the breakpoint shows the correct time but the NSLog
prints the wrong time off by 1 minute and 15 seconds (Breakpoint shows: 0000-12-30 09:00:00 UTC but NSLog prints Sat Dec 30 08:58:45 0000):
Here's my code along with the breakpoint and NSLog output in comments next to it:
NSLog(@"Timezone: %@",[NSTimeZone localTimeZone]);//Timezone: Local Time Zone (Europe/London (GMT) offset 0)
NSLocale *locale = [NSLocale currentLocale];
NSCalendar *myCalendar = [NSCalendar currentCalendar];
[myCalendar setLocale:locale];
[myCalendar setTimeZone:[NSTimeZone localTimeZone]];
NSLog(@"TZ: %@",myCalendar.timeZone);//TZ: Local Time Zone (Europe/London (GMT) offset 0)
NSDateFormatter *timeFormatter = [NSDateFormatter new];
[timeFormatter setDateFormat:@"h:mm a"];
[timeFormatter setLocale:locale];
[timeFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* dateComps = [myCalendar components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:[timeFormatter dateFromString:@"9:00 AM"]];
NSDate *myDate1 = [myCalendar dateFromComponents:dateComps];//Breakpoint shows: 0000-12-30 09:01:15 UTC
NSLog(@"myDate1: %@",myDate1); // myDate1: Sat Dec 30 09:00:00 0000
//----------------Explicitly specified timeZoneWithAbbreviation GMT:
NSCalendar *myCalendarExplicitGMT = [NSCalendar currentCalendar];
[myCalendarExplicitGMT setLocale:locale];
[myCalendarExplicitGMT setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSLog(@"TZ: %@",myCalendarExplicitGMT.timeZone);//TZ: GMT (GMT) offset 0
NSDateComponents* dateCompsUsingExplicitGMT = [myCalendarExplicitGMT components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:[timeFormatter dateFromString:@"9:00 AM"]];
NSDate *myDate2 = [myCalendarExplicitGMT dateFromComponents:dateCompsUsingExplicitGMT];//Breakpoint shows: 0000-12-30 09:00:00 UTC
NSLog(@"myDate2: %@",myDate2); // myDate2: Sat Dec 30 08:58:45 0000