简体   繁体   中英

Converting date from one format to other returns nil in objective c

I am trying to convert a date that come in "2017-12-05T00:00:00-0500" format to Dec 05 .For that I am using following code but it returns nil every time. I don't know what is wrong in this code.Kindly review the code and let me know my mistake.Any kind of guidance in this direction would be greatly appreciated. Thanks in advance!

 [dtF setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"];
        NSDate *d = [dtF dateFromString:[dic valueForKey:@"weight_date"]];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@" YYYY-MM-DD hh:mm:s"];
        NSString *st = [dateFormat stringFromDate:d];
        NSLog(@"%@",st);
NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dtF setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *d = [dtF dateFromString:[dic valueForKey:@"weight_date"]];//@"2017-12-05T00:00:00-05:00"
[dateFormat setDateFormat:@"MMM dd"];
NSString *st = [dateFormat stringFromDate:d];
NSLog(@"%@",st);

Your date format is wrong i have made changes please check answer.

Check below code i have replace your dic with date that you have posted in question:

NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
[dtF setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *d = [dtF dateFromString:@"2017-12-05T00:00:00-0500"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMM dd"];
NSString *st = [dateFormat stringFromDate:d];
NSLog(@"%@",st);

As I tested ur code, I came to know that dtf is not returning a value d is nil

So format for dtf should be

yyyy-MM-dd'T'HH:mm:ss-SSSS

Then replace rest with this.

NSDate *d = [dtF dateFromString:[dic valueForKey:@"weight_date"]];
[dtF setDateFormat:@"MMM dd"];
NSString *st = [dtF stringFromDate:d];
NSLog(@"%@",st);

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