简体   繁体   English

将日期从一种格式转换为另一种格式在目标c中返回nil

[英]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. 我正在尝试将“ 2017-12-05T00:00:00-0500”格式的日期转换为Dec05。为此,我正在使用以下代码,但每次都返回nil。 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: 检查以下代码,我已用有问题的日期替换了您的dic:

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 当我测试您的代码时,我知道dtf不返回值d为nil

So format for dtf should be 所以dtf的格式应该是

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

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

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