iOS 15.4 Beta 12-Hour Time dateFromString nil

Hello, I get nil from api 'dateFromString' in iOS 15.4 Beta when my Date & Time setup to 12-Hour Time.

NSDateFrommatter *formatter = [[NSDateFormmater alloc] init]; 
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = @"2022-02-18 17:05:35";
// newDate is nil
NSDate *newDate = [formmater dateFromString:dateString];

Does anyone else have this problem ?

Will the release version fix this problem ? is

Replies

Your code is not correct. If you use NSDateFormatter to parse a fixed-format date, you must pin the locale to en_US_POSIX. Without that you can run into all sorts of weird problems. Indeed, the fact that this is returning nil is a good thing; in some circumstances it’ll silently return a date that’s roughly 500 years off )-:

QA1480 NSDateFormatter and Internet Dates has the full story here.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

  • We have tested pin the locale to en_US_POSIX, It did solve our problem. I wonder, the iOS version befroe 15.4 need not to add this.

Add a Comment

We have tested pin the locale to en_US_POSIX, It did solve our problem.

Yay!

I wonder, the iOS version befroe 15.4 need not to add this.

They did, you just didn’t discover that in your testing. For example, if you had tested on a device with the current locale set to the Buddhist calendar, you would have noticed a problem immediately [1].

As to why 15.4 caused you to notice this, it’s hard to say. The default locale settings change frequently, and it seems that one of those changes has intersected with your test matrix so that you’ve now notice the problem.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] I once helped an Australian bank debug a problem where their dates were off by about 500 years, but only for a small subset of their customers who happened to all live in Thailand. It seems that those customers had selected the Buddhist calendar, and were triggering exactly this issue.