To convert a particular format to NSDate [closed]

烂漫一生 提交于 2019-12-13 11:27:46

问题


I am getting a date component from web service as @"2014-01-08T00:00:00.000Z". I need to convert it into a date only providing me with year , month and date. Please help


回答1:


Use this code to get the Current Date

NSDateFormatter *dateFor=[[NSDateFormatter alloc]init];
NSString *currentDateString = @"2014-01-08T21:21:22.737+05:30";

[dateFor setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];        
NSDate *currentDate = [dateFor dateFromString:currentDateString];

NSLog(@"CurrentDate:%@", currentDate);



回答2:


If you need the output year- month -date in like that format then use below code. Also you need to convert the format into specified below format:-

NSString *currentDateString = @"2014-01-08T00:00:00.000Z";
self.dateFormatter=[[NSDateFormatter alloc]init];
[self.dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate *currentDate = [self.dateFormatter dateFromString:currentDateString];
[self.dateFormatter setDateFormat:@"yyyy-MM-dd"];
    currentDateString=[self.dateFormatter stringFromDate:currentDate];
NSLog(@"CurrentDate:%@", currentDateString);

Output:-

CurrentDate:2014-01-08



回答3:


After getting the date from string again change the format of dateformatter and then get the string using formatter.

NSString *currentDateString = @"2014-01-08T21:21:22.737+05:30";

NSDateFormatter *dateFor=[[NSDateFormatter alloc]init];
[dateFor setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];        
NSDate *currentDate = [dateFor dateFromString:currentDateString];
[dateFor setDateFormat:@"MMMM dd, yyyy"];

// above format will show date as Dec 31, 2013 something like this
// can use other format as well like. [dateFor setDateFormat:@"yyyy-MM-dd"]

NSString *dateString =  [dateFor stringFromDate:currentDate];


来源:https://stackoverflow.com/questions/20994688/to-convert-a-particular-format-to-nsdate

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