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

Sus*_*nna 5 iphone compilation date 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];  
Run Code Online (Sandbox Code Playgroud)

好的,我放弃了.为什么aDate有时会返回为零?

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

小智 20

如果手机的区域设置不是美国(或等效设置),则可以返回nil.

尝试将formatter的语言环境设置为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];  
Run Code Online (Sandbox Code Playgroud)

  • `__DATE__`宏在编译时确定,并用该格式的字符串文字替换.但是,您将该字符串转换为NSDate会在运行时发生,该运行时受当前区域的影响. (5认同)

San*_*hry 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];
Run Code Online (Sandbox Code Playgroud)