4

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?

CLDev
  • 1,076
  • 3
  • 12
  • 20
  • There is no time zone for date, so if you form the date with proper timezone, you can calculate the difference without too many conversions. – Anupdas Aug 08 '13 at 11:24

1 Answers1

2

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.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • I saw a link http://stackoverflow.com/questions/13917938/change-nsdate-from-one-time-zone-to-another. Which converts the [NSDate date] into GMT and then convert my dateB into GMT as well and then calculate the time difference. Is this an acceptable solution or there is a better way to do this? – CLDev Aug 08 '13 at 17:07
  • Yes, this is already the solution, but it does not convert the date into GMT, it interprets the string as being a time in the GMT time zone. Take that answer and then replace `GMT` with `PDT` (this is your source time zone). Now you have a date object, _and that date object is not bound to a time zone_ (that part is important to understand: NSDate is time zone neutral). If you want to store or transmit the date, this is what you want to store or transmit. _Then_ for displaying, you again feed it to a NSDateFormatter, this time you set the target time zone and convert the date into a string. – DarkDust Aug 08 '13 at 17:41