5
//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 を返すのはなぜですか?

コメントアウトされた行を使用するか、それとも一致する置換行を使用するかは重要ですか?

4

2 に答える 2

22

電話の地域設定が米国 (または同等) でない場合は、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];  
于 2010-05-19T02:56:47.513 に答える
9

ARC対応コードのDyingCactusの回答を少し変更します(コピーアンドペーストを簡単にするため):

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];
于 2014-01-10T15:59:26.643 に答える