iOS NSDateFormatter needs NSLocale even it's U

2019-02-24 21:43发布

I have a doubt that I cannot understand why is the way it is and I appeal to the Gods of this site :)

I have a date coming like this:

"1982-01-01T00:00:00Z" 

As I'm displaying whatever the server sends (I know, customer requirement, not good practice...), I'm forcing the device to have that TimeZone with the following method, simplified without error checking, not optimized, and all that kind of things:

+ (NSString *) yearStringFromDate: (NSDate *) date
{
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"YYYY"];
    [formatter setTimeZone:[self timezoneForSIHF]];

    return [formatter stringFromDate:date];    
}

This should be UTC, BUT if I don't set the locale I'm getting, and JUST sometimes the incorrect year. So by adding this I get the year correct for all cases:

[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];

For further info, I'm testing in a real device and simulator with different languages (en, de, es).

  • Why is this?
  • Why does the locale affect the date even though the timeZone is correct?
  • Why sometimes is working with some dates and sometimes it's not? For example, 1982 is returning without setting the locale, 1981 and if I set it 1982. This doesn't happen with 1980, returning in both cases 1980 (or 1987, or ...)

Thanks in advance for all your replies :D Cheers!

2条回答
做个烂人
2楼-- · 2019-02-24 22:26

When converting ISO 8601/RFC 3339 date string to NSDate object, one uses the en_US_POSIX locale in case the user is not using a Gregorian calendar. See Technical Q&A 1480.

In your case, though, you are trying to get year string representation from date object. In that case you might not need en_US_POSIX. That's only necessary if you need to use Gregorian calendar regardless of what sort of calendar the device might currently be using.

As noted by others, though, you should be using yyyy and not YYYY. The former returns the calendar year. The latter returns the year, in "Week of Year" based calendars, which may not always be the same value as calendar year.

See the date formatting patterns for a discussion contrasting y and Y.

By the way, if you really need the year component of the date, you can also use the NSDateComponents related methods of NSCalendar.

查看更多
乱世女痞
3楼-- · 2019-02-24 22:28

Use yyyy instead of YYYY.

Reference.

查看更多
登录 后发表回答