繁体   English   中英

NSDate从String返回nil

[英]NSDate from String returning nil

我将日期存储为字符串,格式为: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]];

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

您在dateformat中设置了错误的格式。 因此它将始终返回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;

}

请在此处参考日期格式化程序的日期格式:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM