2014-01-08 69 views
-4

我从@“2014-01-08T00:00:00.000Z”从Web服务获取日期组件。我需要将它转换为只提供年份,月份和日期的日期。请帮助将特定格式转换为NSDate

+0

http://unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns – Desdenova

+0

这个问题已经被问超过10000次,下一次尝试使用谷歌 –

回答

2

使用此代码来获取当前日期

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

这不是问了什么。他说'给我提供年份,月份和日期。' – Desdenova

+0

@Desdenova,但它提供年,月和日期的日期。 – ChenSmile

+0

当然,但你需要再次格式化,以消除时间。 – Desdenova

3

如果需要输出年 - 月-date在这样的格式,然后用下面的代码。另外你需要的格式转换成以下格式指定: -

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

输出: -

CurrentDate:2014-01-08 
+0

@Hussan Shabbir我编辑答案。你的回答完美无需编辑抱歉我的错误。 –

+0

其正常np :) –

+0

谢谢你采取冷静.. –

1

正从字符串的日期再次改变dateformatter的格式,然后经过使用获得的字符串格式化。

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]; 
相关问题