开发者

iPhone SDK Objective-C __DATE__ (compile date) can't be converted to an NSDate

//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. Wh开发者_开发问答y would aDate sometimes return as nil?

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


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];  


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜