0

I have to set a format string for a DateFormatter to convert a NSString to a NSDate.

The string is in the format: 2011-01-31 12:45:00 +0200 (y-m-d h:m:s timezone)

I'm using the format: @"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'Z" , but the timezone is converted to +0000 and the hour is adjusted, so a string like: 2011-01-31 12:45:00 +0200 is converted to: 2011-01-31 10:45:00 +0000

The Code is here:

- (NSDate *) dateForString: (NSString *)dateString
{
    NSDateFormatter *dateFormatter;
    NSLocale *enUSPOSIXLocale;
    NSDate  *date;

    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];

    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'Z"];
    // [dateFormatter  setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    date = [dateFormatter dateFromString:dateString];
    return date;
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
David Casillas
  • 1,801
  • 1
  • 29
  • 57

2 Answers2

1

This is absolutely expected behaviour when using NSDate - NSDate represents a moment in time so in your case the 2 date/times are equivalent.

Just make sure when you display the date using the a dateFormatter you set the timezone on the date formatter to how you want it displayed.

Daniel Broad
  • 2,512
  • 18
  • 14
0

Have a look at setTimeZone: in http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

Some more info can also be found here: NSDate - Convert Date to GMT (maybe duplicate?)

Community
  • 1
  • 1
Christian Beer
  • 2,027
  • 15
  • 13