iPhone SDK Objective-C __DATE__(编译日期)无法转换为 NSDate

发布于 2024-09-02 05:18:03 字数 435 浏览 2 评论 0原文

//NSString *compileDate = [NSString stringWithFormat:@"%s", __DATE__];
NSString *compileDate = [NSString stringWithUTF8String:__DATE__];

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];

[df setDateFormat:@"MMM d yyyy"];   
//[df setDateFormat:@"MMM dd yyyy"];    

NSDate *aDate = [df dateFromString:compileDate];  

好吧,我放弃了。为什么 aDate 有时会返回 nil?

如果我使用注释掉的行...或其匹配的替换行,应该重要吗?

//NSString *compileDate = [NSString stringWithFormat:@"%s", __DATE__];
NSString *compileDate = [NSString stringWithUTF8String:__DATE__];

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];

[df setDateFormat:@"MMM d yyyy"];   
//[df setDateFormat:@"MMM dd yyyy"];    

NSDate *aDate = [df dateFromString:compileDate];  

Ok, I give up. Why would aDate sometimes return as nil?

Should it matter if I use the commented-out lines... or their matching replacement lines?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷夜 2024-09-09 05:18:03

如果手机的区域设置不是美国(或同等设置),它可以返回 nil。

尝试将格式化程序的区域设置设置为 en_US:

NSString *compileDate = [NSString stringWithUTF8String:__DATE__];
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"MMM d yyyy"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:usLocale];
[usLocale release];
NSDate *aDate = [df dateFromString:compileDate];  

It can return nil if the phone's Region setting is not US (or equivalent).

Try setting the formatter's locale to en_US:

NSString *compileDate = [NSString stringWithUTF8String:__DATE__];
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"MMM d yyyy"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:usLocale];
[usLocale release];
NSDate *aDate = [df dateFromString:compileDate];  
羁绊已千年 2024-09-09 05:18:03

稍微修改 DyingCactus 对 ARC 启用代码的答案(为了更容易复制粘贴):

NSString *compileDate = [NSString stringWithUTF8String:__DATE__];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMM d yyyy"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:usLocale];
NSDate *aDate = [df dateFromString:compileDate];

Slightly modifying DyingCactus' answer for ARC enabled code (for easier copying-n-pasting):

NSString *compileDate = [NSString stringWithUTF8String:__DATE__];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMM d yyyy"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:usLocale];
NSDate *aDate = [df dateFromString:compileDate];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文