简体   繁体   中英

iOS Date Formatter Returns Null

I have searched the internet for a solution but have not been able to solve my problem.

I have a date that I am formatting but it always returns null.

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.sss.ZZZZ"];
    NSString *dueDateString = [NSString stringWithFormat:@"2014-07-11T15:21:42.207+0200"];
    NSDate *dateFromApi = [dateFormatter dateFromString:dueDateString];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSString *finalDateString = [dateFormatter stringFromDate:dateFromApi];
    NSLog(@"dueDateString %@", dueDateString);
    NSLog(@"dateFromApi %@", dateFromApi);
    NSLog(@"finalDateString%@", finalDateString);

I do not know what I am doing wrong but the format above seems to work if I use this format 0001-01-03T00:00:00.000+0200 I get an output of 0001/01/02. As soon as it changes like this 2014-07-11T15:21:42.207+0200 it does not work and always returns null?

Please use below code

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
NSString *dueDateString = [NSString stringWithFormat:@"2014-07-11T15:21:42.207+02:00"];
NSDate *dateFromApi = [dateFormatter dateFromString:dueDateString];
[dateFormatter setDateFormat:@"yyyy/MM/dd"];
NSString *finalDateString = [dateFormatter stringFromDate:dateFromApi];
NSLog(@"dueDateString %@", dueDateString);
NSLog(@"dateFromApi %@", dateFromApi);
NSLog(@"finalDateString%@", finalDateString);

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