Date formatting in iOS 9 not working [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-01 19:12:17

问题


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:


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")


来源:https://stackoverflow.com/questions/32932484/date-formatting-in-ios-9-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!