Search code examples
iosobjective-ciphonetimezonenstimezone

iOS: Timezone issue occurring


Seems that apple timezone is having problems for me right now. I tested the following code below and it isn't working correctly. This is what I have so far.

 NSDate *today = [NSDate date];

 NSDateFormatter *estDf = [[NSDateFormatter alloc] init];
 [estDf setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
 [estDf setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

  NSString *stringDate = [estDf stringFromDate:today];
  NSDate *todaydateadjusted = [estDf dateFromString:stringDate];

  NSLog(@"Todays date is %@",[estDf stringFromDate:todaydateadjusted]);

This is my NSLog response.
Todays date is 2015-03-09 16:25:02

I expected 17:25:02 time not 16:25:02. Since it is 5 o' clock p.m in est time right now it should print out 17 instead of 16. Anyone else having this problem? Perhaps something is wrong with my code.


Solution

  • There is daylight saving time right now. Shouldn't you use EDT instead?

    The other thing is time zone name vs. time zone abbreviation. Take a look at this example - I wrote it in Swift, but I think it should be easy to understand and translate to ObjC.

    var now = NSDate()
    var df = NSDateFormatter()
    df.timeZone = NSTimeZone(abbreviation: "EDT")
    //df.timeZone = NSTimeZone(name: "EDT") <- wrong
    df.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let edt = df.stringFromDate(now)
    

    If you want to use the full time zone name, use for example df.timeZone = NSTimeZone(name: "America/New_York")