2
votes

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?

2
... and that's what happens for other conversions: stringToDate("2011-06-24 08:00:00.000 +0200") = '2011-06-23 22:00:00 +0000' stringToDate("2011-07-24 08:00:00.000 +0200") = '2011-07-23 22:00:00 +0000' - Ivan Leonardi
Not sure I understood your problem with this "stringToDate("2011-06-24 08:00:00.000 +0200") = '2011-06-23 22:00:00 +0000' stringToDate("2011-07-24 08:00:00.000 +0200") = '2011-07-23 22:00:00 +0000' " But if your issue was that regardless what input string you passed, the return date strings are the same... if this is the case, check to make sure the strings you are passing are different. - user523234

2 Answers

1
votes

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.

1
votes

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.