Still having NSDateFormatter result issues even wi

2019-07-17 11:32发布

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.

1条回答
戒情不戒烟
2楼-- · 2019-07-17 11:59

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

查看更多
登录 后发表回答