简体   繁体   中英

NSDate from String returning nil

I am storing dates as strings in the format: 2018-07-10 21:00:29 +0000

I created a formatter to convert the strings back into dates:

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]];

However, the date that is returned is always nil. Does anyone know what I'm doing wrong?

You set the wrong format in the dateformat. So it will always return the nil value.

The following method can return the date in the NSDate format.

-(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;

}

Refer to date formatter date formats here :

You need to update your date format to something like: "yyyy-MM-dd HH:mm:ss Z"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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