dateformatter producing wrong date

Discussion in 'iOS Programming' started by johnmerlino, Jul 24, 2012.

  1. johnmerlino macrumors member

    Oct 22, 2011
    #1 returns 02/13/2012 03:40:02 PM

    I try to format it:

    - (NSString *)formatTimeFor:(Report *)report
            NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
            [dateFormat setDateFormat:@"MM/dd/YYYY HH:mm:ss a"];
            NSDate *date = [dateFormat dateFromString:report.time];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setTimeZone:[NSTimeZone systemTimeZone]];
            [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss a"];
            NSString *dateTimeStr = [formatter stringFromDate:date];
            return [NSString stringWithFormat:@"%@", dateTimeStr];
        else {
            return  @"No time specified";
    and it returns 2011/12/25 07:40:02 AM
  2. Duncan C macrumors 6502a

    Duncan C

    Jan 21, 2008
    Northern Virginia

    You are creating a date formatter that assumes your input date string is in the GMT time zone, and then converting that date into a new date string in the user's local time zone. Unless the user is in GMT, your code will give the wrong date/time.

    Get rid of the line that sets the first date formatter to GMT. Let both date formatters assume the user's current time zone. Alternately, make BOTH date formatters use GMT.

Share This Page