Se agregan 6 horas al objeto NSDate cuando se usa NSDateFormatter

I am trying to format a date object and I am noticing on the string I am passing in; 6 hours is being added to my time. This seems to be associating my date time object to GMT.

Mi código:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd h:mm:ss a"];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *date = [formatter dateFromString:@"2012-02-01 03:38:12 AM"];



    NSLog(@"%@", date);

El resultado es:

2012-02-01 09:38:12 +0000

I have tried this with and without the setTimeZone and it does not matter. Any ideas on why this is displaying as GMT time?

Thanks, Flea

preguntado el 01 de febrero de 12 a las 22:02

2 Respuestas

The date that your formatter creates is not associated with any timezone, but the description método de NSDate (Que es que NSLog uses for the output) converts any date to UTC. You would have to use another (or the same) date formatter's stringFromDate: method to print it with a different time zone.

Respondido 02 Feb 12, 02:02

thanks omz, when I did this, it worked: [formatter stringFromDate:date]; NSLog(@"%@", [formatter stringFromDate:date]); result: 2012-02-01 03:38:12 PM - Pulga

All NSDates are absolute times, meaning that 3:00 AM central time in the United States is 9 AM UTC. I suspect that your systemTimeZone is central time in the United States.

NSLog always shows times in UTC.

If you want to see, as a string, what the time is in your time zone, then you can use the same date formatter stringFromDate: method, and make the you set the time zone of the date formatter to that time zone.

NSLog date formatting is an annoyance because it leads to the kind of confusion you are experiencing.

Respondido 02 Feb 12, 02:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.