iPhone SDK Objective-C __DATE__ (compile date) can

2020-07-13 07:32发布

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

2条回答
放我归山
2楼-- · 2020-07-13 07:45

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];  
查看更多
男人必须洒脱
3楼-- · 2020-07-13 08:07

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];
查看更多
登录 后发表回答