【问题标题】:iPhone SDK Objective-C __DATE__ (compile date) can't be converted to an NSDateiPhone SDK Objective-C __DATE__(编译日期)无法转换为 NSDate
【发布时间】:2010-05-19 02:24:50
【问题描述】:
//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?

我是否使用注释掉的行...或它们匹配的替换行是否重要?

【问题讨论】:

  • 不值得回答的小提示:由于预处理器的工作方式,要将 DATE 作为 NSString,您可以简单地编写 @__DATE__

标签: iphone date compilation nsdate nsdateformatter


【解决方案1】:

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

【讨论】:

  • 哇。我会试试的。我认为 DATE 总是会在编译时确定......并且基于我正在编译它的机器(英语)。因此 DATE始终 采用“2010 年 2 月 1 日”格式。 (我不是要求在运行时确定日期......或基于用户的本地设置。)
  • __DATE__ 宏在编译时确定并替换为该格式的字符串文字。但是您将该字符串转换为 NSDate 发生在受当前区域影响的运行时。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2011-06-01
    • 2018-01-28
    • 2011-03-20
    • 2023-03-10
    • 2014-01-06
    • 2010-12-24
    相关资源
    最近更新 更多