Reputation: 1911
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;
}
Upvotes: 0
Views: 358
Reputation: 2522
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.
Upvotes: 1
Reputation: 2025
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?)
Upvotes: 0