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

时间:2010-05-19 02:24:51

标签: iphone date compilation nsdate nsdateformatter

//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?

如果我使用已注释掉的线条或其匹配的替换线是否重要?

2 个答案:

答案 0 :(得分:20)

如果手机的区域设置不是美国(或等效设置),则可以返回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];  

答案 1 :(得分:9)

略微修改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];