How change the date format which is stored in string? Objective c [duplicate]

痞子三分冷 提交于 2019-12-21 06:08:09

问题


Possible Duplicate:
how to convert datetime format in NSString?

I have stored date in string from json parsing. The format of date is 2011-1-24. Now i want to convert into MM-dd-YYYY format. For that i am using this code

NSString *stringDate =[NSString stringWithFormat:@"%@",[list_date objectAtIndex:indexPath.row]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy"];
NSDate *date  = [dateFormatter dateFromString:stringDate];
NSString *newDate = [dateFormatter stringFromDate:date];

But it show null value. What is problem in this code?

Thanks in advance...


回答1:


It is different from @Mayur Joshi's answer though it looks to be same.

This is sure to work for you.

 NSString *dateString = @"2011-09-19";
 NSDateFormatter *format = [[NSDateFormatter alloc] init];
 [format setDateFormat:@"yyyy-MM-dd"];
 NSDate *date = [format dateFromString:dateString];
 [format setDateFormat:@"MM-dd-yyyy"];
 NSString* finalDateString = [format stringFromDate:date];
 [format release];

I hope this helps you.

If you need any help on this then please leave a comment below.

Also you can refer to this link for more help. This link is really similar to what you want, only the target date Format is different.

How to convert date string into format "17 Nov 2010"




回答2:


 NSString *dateStr = @"2011-1-24";

 //OR if you have date then declare dateStr like this, 
 NSString *dateStr = [NSString stringWithFormat:@"%@",yourDate];

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"YYYY-M-dd"];
 NSDate *date = [dateFormat dateFromString:dateStr];
 [dateFormat setDateFormat:@"MM-dd-YYYY"];
 NSString* temp = [dateFormat stringFromDate:date];
 [dateFormat release];

 NSLog(@"%@",temp);


来源:https://stackoverflow.com/questions/7466801/how-change-the-date-format-which-is-stored-in-string-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!