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