简体   繁体   中英

Unexpected behavior with NSDateFormatter on iOS 9.1

I have this code:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm Z"];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
[dateFormat setLocale:[NSLocale currentLocale]];
NSString *sDate = [dateFormat stringFromDate:_datePicker];

_datePicker comes from this and datePicker is a UIDatePicker

_datePicker = datePicker.date;

This was working ok in iOS 7 fore sure, and now I'm testing in 9.1

So if the phone settings is set to show the time in the 24h format its ok, but if I change the settings to none 24h format I have a estrange behavior:

if is set to 24h the output is:

在此输入图像描述

But if i change it to non 24h is:

在此输入图像描述

在此输入图像描述

As you can see is like is combining the 2 formats it adds for example the 13 of the 1 pm to the hour 131:00 or at 6 pm will be 186:00.

Is there a work around to always get the time in the 24h format?

Thanks in advance.

Hi I have sean this approach in another page and I have change the code to this:

NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy-MM-dd HH:mm Z"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone localTimeZone]];

NSString *sDate = [rfc3339DateFormatter stringFromDate: _datePicker];

And now is working properly but I'm not sure that this is the correct way.

I hope this helps someone in the future.

UPDATE: This is where I got the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM