简体   繁体   English

NSDateFormatter dateFromString无

[英]NSDateFormatter dateFromString nil

I know the question exists already, but the given answers don't help me out. 我知道这个问题已经存在,但是给出的答案并没有帮助我。

birthday has the value: Jun 29, 2013, 8:45 AM 生日的值: 2013年6月29日,上午8:45

Here is my code: 这是我的代码:

NSDate* now = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
NSDate *birthdayDate = [dateFormatter dateFromString:birthday];

NSLog(@"%@", birthdayDate);

birthdayDate is always nil BirthdayDate始终为零

What should I do? 我该怎么办?

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. 在大多数情况下,最佳选择的语言环境是en_US_POSIX,该语言环境专门设计用于产生美式英语结果,而不考虑用户和系统偏好。 en_US_POSIX is also invariant in time (if the US, at some point in the future, changes the way it formats dates, en_US will change to reflect the new behavior, but en_US_POSIX will not), and between platforms (en_US_POSIX works the same on iPhone OS as it does on OS X, and as it does on other platforms). en_US_POSIX的时间也不变(如果美国在将来某个时候改变其格式化日期的方式,en_US将更改以反映新的行为,但是en_US_POSIX不会),以及平台之间(en_US_POSIX在iPhone上的作用相同)操作系统,如在OS X上以及在其他平台上一样)。

// String to Date
NSString *birthday = @"Jun 29, 2013, 8:45 AM";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM dd, yyyy, HH:mm a"];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
// Setting the locale to POSIX ensures that
// the user's locale won't be used
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *birthdayDate = [dateFormatter dateFromString:birthday];

NSLog(@"birthdayDate:%@", birthdayDate);

// Date to String
[dateFormatter setLocale:[NSLocale currentLocale]];
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
NSString *originalBirthday = [dateFormatter stringFromDate:birthdayDate];

NSLog(@"originalBirthday=%@",originalBirthday);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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