NSString to NSDate conversion problem: always the same date!
Here is my class method for parsing a NSString
to a NSDate
object. Here is the code:
+ (NSDate *) stringToDate:(NSString *) string { NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.AAA Z"]; NSDate *date = [dateFormatter dateFromString:string]; NSLog(@"stringToDate(\"%@\") = '%@'", string, date); [dateFormatter release]; return date; }
and running it i 开发者_如何学运维get the following output:
stringToDate("2011-07-07 16:26:07.000 +0200") = '2011-07-06 22:00:00 +0000' stringToDate("2011-07-07 16:26:17.000 +0200") = '2011-07-06 22:00:00 +0000'
... the same output! Can you help me?
If I get you right, your problem is that the two dates are not exactly the same.
If this is the problem, the line
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
is responsible for it. It is converting the given time object to GMT+00 time zone.
You should write:
NSLog(@"stringToDate(\"%@\") = '%@'", string,
[dateFormatter stringFromDate:date]);
Otherwise, NSLog
calls the description
method of your date
object. Here is what the documentation says about this method:
description
Returns a string representation of the receiver.
-(NSString *)description
Return Value
A string representation of the receiver in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”).
As you can see, the format is not exactly the same as the one you use.
edit
Try changing the dateFormat parameter of your dateFormatter
to yyyy-MM-dd HH:mm:ss Z
and use [dateFormatter stringFromDate:date]
to display your date.
精彩评论