i_mush
i_mush

Reputation: 216

Still having NSDateFormatter result issues even with NSTimezone properly set, why?

The result is still a day before, I'm just asking myself why, because the NSTimeZone is properly set and is the right one for my country (italy, rome) here's my stub of code, any ideas?

    NSString *dateString = @"03/07/2008";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setFormatterBehavior:[NSDateFormatter defaultFormatterBehavior]];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *dateFromString = [formatter dateFromString:dateString];
    [formatter release];

the result in dateFromString is this 2008-07-02 22:00:00 +0000.

I've looked for other solutions but the common answer was to set the timezone correctly, in my case it is set properly but the problem still remains.

Upvotes: 2

Views: 756

Answers (1)

Joe
Joe

Reputation: 57179

That is correct because by default the NSDate will return a UTC date in its description +0000. You are a couple of hours ahead of UTC so you get 22:00:00 for the day prior. I am -5 and my result UTC is 2008-07-03 04:00:00 +0000 (DST). The date is correct, it is just being displayed in UTC, if you are trying to display it correctly somewhere just use the date formatter to get a string again.

...
NSDate *dateFromString = [formatter dateFromString:dateString];
NSString *stringFromDate = [formatter stringFromDate:dateFromString];
[formatter release];

NSLog(@"%@ : %@", dateFromString, stringFromDate);

2008-07-03 04:00:00 +0000 : 03/07/2008

Upvotes: 6

Related Questions