ios - NSDateFormatter dateFromString 无

标签 ios nsdate nsdateformatter

我知道问题已经存在,但给出的答案对我没有帮助。

生日的值为:Jun 29, 2013, 8:45 AM

这是我的代码:

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

生日日期始终为零

我该怎么办?

最佳答案

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

// 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);

关于ios - NSDateFormatter dateFromString 无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31110155/

相关文章:

objective-c - 将 NSString 转换为 NSDate 的问题

ios - NSDateFormatter日期转换不正确

swift - 如何在 Swift 中以短格式获取当前日期

ios - render回调函数和input回调函数有什么区别

ios - "Firebase_VERSION is not defined: add -DFirebase_VERSION=... to the build invocation"

objective-c - 仅获取两个日期之间的周末

ios - 在 iOS 中计算 hh.mm.ss 格式的时间间隔

ios - 在 iOS 中我可以使用什么来代替 NSBitmapImageRep? (水波纹示例)

用于 UIView 的 iOS viewDidLoad

ios - 时间戳中的日期变得错误