我在将 NSString 转换为 NSDate 并返回格式化的 NSString 时遇到问题。代码片段在 iOS 模拟器上没有任何问题,但在我的 iPhone 4 上不起作用。
NSString *pubDate = @"Tue, 18 Oct 2011 05:00:00 +0100";
NSDateFormatter *formater1 = [[NSDateFormatter alloc] init];
[formater1 setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
NSDate *d = [formater1 dateFromString:pubDate];
NSLog(@"d: %@", d);
NSDateFormatter *formater2 = [[NSDateFormatter alloc] init];
[formater2 setDateFormat:@"dd MMM yyyy"];
NSString *k = [formater2 stringFromDate:d];
NSLog(@"k: %@", k);
[formater1 release];
[formater2 release];
模拟器的输出是:
d: 2011-10-18 04:00:00 +0000
k: 18 Oct 2011
设备上的输出是:
d: (null)
k: (null)
有什么建议吗?
最佳答案
您需要在日期格式化程序上设置语言环境。
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
//...
formater1.locale = locale;
//...
formater2.locale = locale;
//...
[locale release];
如果您不设置语言环境,则用户的设置可以更改提供的字符串以符合用户的设置,例如将 12 小时制更改为 24 小时制,反之亦然。
关于iphone - NSString 到 NSDate 不适用于 iDevice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7804863/