Reputation: 110
I've written a method that accepts a NSDate object and should turn it into a NSDate object with EST time zone. The way I've seen other people accomplish this is by using a date formatter to change the date to a string with the specified time zone. The issue is when I try to change that string back to a NSDate object using "dateFromString".
- (NSDate*)turnToEST:(NSDate*)date
{
NSLog(@"turnToEST called with date %@", date);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"EST"]];
NSString *stringFromDate = [dateFormatter stringFromDate:date];
NSLog(@"date formatted is %@", stringFromDate);
NSDate *dateFromString = [[NSDate alloc] init];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
[dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
dateFromString = [dateFormatter2 dateFromString:stringFromDate];
NSLog(@"date has been changed to %@", dateFromString);
return date;
}
With output...
turnToEST called with date 2013-12-19 14:15:17 +0000
date formatted is 2013-12-19 09:15:17
date has been changed to 2013-12-19 14:15:17 +0000
I'm not sure why this is any different than
Converting NSString to NSDate (and back again)
Upvotes: 0
Views: 1353
Reputation: 14816
NSDate
values do not have an associated time zone, they represent an abstract moment in time. So "a NSDate object with EST time zone" isn't a thing that exists. Time zones only come into play when formatting them for output, or trying to do calendar-based math.
NSLog
always uses UTC when printing its output.
So you're taking a moment in time, formatting it to a string in a particular time zone, and then parsing it back into the same moment in time. That's working as intended.
Upvotes: 4