【问题标题】:NSDate from String returning nilNSDate 来自 String 返回 nil
【发布时间】:2023-03-14 04:13:02
【问题描述】:

我将日期存储为字符串,格式为:2018-07-10 21:00:29 +0000

我创建了一个格式化程序来将字符串转换回日期:

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
[formatter setLocale:[NSLocale currentLocale]];
NSDate *date = [formatter dateFromString:[chore getDate]];

但是,返回的日期始终为零。有谁知道我做错了什么?

【问题讨论】:

  • 字符串中的T在哪里,小数秒(SSS)在哪里?
  • 您使用了错误的语言环境。解析固定格式字符串时需要使用en_US_POSIX

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

您在日期格式中设置了错误的格式。所以它总是会返回 nil 值。

下面的方法可以返回NSDate格式的日期。

-(NSDate *)convertDate :(NSString *)date1  //the argument date1 is the string date you used

{   
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z"; // the format which you used in the string date
    [formatter setLocale:[NSLocale currentLocale]]; //This for set the Locale .It is not compulsory.
    NSDate *date = [formatter dateFromString:date1];
    return date;

}

【讨论】:

    【解决方案2】:

    参考日期格式器日期格式here:

    您需要将日期格式更新为: "yyyy-MM-dd HH:mm:ss Z"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      相关资源
      最近更新 更多