To convert a particular format to NSDate [closed]

2019-09-22 05:30发布

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

3条回答
Emotional °昔
2楼-- · 2019-09-22 06:05

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);
查看更多
该账号已被封号
3楼-- · 2019-09-22 06:09

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
查看更多
来,给爷笑一个
4楼-- · 2019-09-22 06:14

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];
查看更多
登录 后发表回答