Date formatting in iOS 9 not working [duplicate]

2020-04-08 01:48发布

I'm have a problem with date formatting in iOS 9, it works ok with iOS 8 and also it works when I'm testing it in simulator with iOS 9, but when a test it on real device with iOS 9 I'm getting null. Below is code that I'm using

NSLog(@"String Date: '%@'", stringDate);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormat dateFromString:stringDate];
NSLog(@"Date: %@", date);

In log I'm getting:

String Date: '8/29/2015 4:13:39 PM'
Date: (null)

Also if I use uppercase h (H or HH) I'm always getting that hour is 10.

1条回答
姐就是有狂的资本
2楼-- · 2020-04-08 01:59

Try setting locale on your date formatter.

[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

From Apple Documentation:

If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences.

EDIT: Swift Version

dateFormat.locale = NSLocale(localeIdentifier: "en_US_POSIX")
查看更多
登录 后发表回答