CLDev
CLDev

Reputation: 1074

NSDate change time zone

I am writing an app that involves time zone. I want to grab the user's device time, lets call that dateA, and I have a target date that will always be in EDT time zone (dateB).

I want to get the difference between the 2 dates and show the user, but in dateB's time zone.

eg:
user device time is 07:30AM PDT, and dateB is 11:00AM EDT.
So the time difference would be 30 minutes.

My algorithm is:
1) Get user device time
2) convert to EDT
3) grab the time difference between dateA and dateB

My issue is, after I get the user's device time [NSDate date], and go through DateFormatter with timezone EDT. The time does not change.

EDIT::

    NSDate *localDate = [NSDate date]; //this will have 7:30AM PDT
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"EDT"]];
    NSString *convertedTimeString = [dateFormatter stringFromDate:localDate];

How come the convertedTimeString does not contain 10:30AM in EDT? What am I doing wrong?

Upvotes: 4

Views: 6534

Answers (1)

DarkDust
DarkDust

Reputation: 92336

A NSDate is stored in a timezone neutral way. It's up to the NSDateFormatter to actually format for a given timezone using -[NSDateFormatter setTimeZone:]. If you want a string from NSDate, there's also -[NSDate descriptionWithCalendarFormat:timeZone:locale:], but it's usually better to use a NSDateFormatter instead.

Upvotes: 2

Related Questions