【问题标题】:NSDate dateFromString: returns nullNSDate dateFromString:返回空
【发布时间】:2014-04-02 14:56:36
【问题描述】:

我看过很多关于这个主题的帖子,但我无法解决我的问题/我想我的格式日期有问题,但我不知道是哪一个。

dateStr = @"Thu, 19 Dec 2013 13:33:58 +0000" // My string I want to convert
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM y HH:m:s Z"]; // Here might be the issue
NSLog(@"Date: %@", [dateFormatter dateFromString:dateStr]);

输出是:

2014-04-02 16:51:02.871 MyApp[3957:60b] Date: (null)

我尝试了一些不同的格式,但我总是得到 null NSDate。

我从 Dropbox API 检索字符串,在文档中它说格式是:

"%a, %d %b %Y %H:%M:%S %z" with strftime or strptime

谢谢

【问题讨论】:

  • 这一年尝试“yyyy”而不是只有一个“y”
  • 你能从 Dropbox 中获取非字符串格式的日期吗?
  • 您的日期转换适用于我(在 iOS 模拟器中),没有问题,因此可能是语言环境问题。尝试将 POSIX 语言环境设置为(例如)此处所示:stackoverflow.com/a/18258115/1187415(还有其他类似的答案)。
  • 好的试试"EEE, dd MMM yyyy HH:mm:ss Z"
  • [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; 是解决方案,谢谢@MartinR

标签: objective-c nsdate nsdateformatter


【解决方案1】:

我注意到 Dropbox“修改”文件日期元数据的 NSDate 转换仅适用于众所周知的语言环境,所以我使用了这种幼稚的方法

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier: @"en_US"]];
    dateFormatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss Z";
    NSDate *dateModified = [dateFormatter dateFromString:dropboxDictionay[@"modified"]];
   [dateFormatter setLocale:  [[NSLocale alloc] initWithLocaleIdentifier: [[NSLocale currentLocale] localeIdentifier]]]; 
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[self.dateFormatter setTimeStyle:NSDateFormatterShortStyle];
myLabel.text = [dateFormatter stringFromDate:dateModified];

为我工作......

迪米特里斯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多