2010-11-10 116 views
1

我有下面的代碼是用來把一個NSDate和當前日期的時間,並將它們合併成一個NSDate。然而,格式化程序設置正確,但它返回的日期甚至與應該的日期不相符。下面是代碼NSDateFormatter沒有返回正確的日期

/* Get the current date and make a formatter to just show the date ONLY */ 
NSDate *currentDate = [NSDate date]; 
NSDateFormatter *curDateFormatter = [[NSDateFormatter alloc] init]; 
[curDateFormatter setDateFormat:@"MM/dd/YYYY"]; 

/* Create a formatter for the time ONLY */ 
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init]; 
[timeFormatter setDateFormat:@"hh:mm"]; 

/* Create a formatter for both date and time */ 
NSDateFormatter *combinedFormatter = [[NSDateFormatter alloc] init]; 
[combinedFormatter setDateFormat:@"MM/dd/YYYY hh:mm"]; 

NSString *combinedDateTime = [NSString stringWithFormat:@"%@ %@", [curDateFormatter stringFromDate:currentDate], [timeFormatter stringFromDate:time]]; 
NSDate *combinedDate = [combinedFormatter dateFromString:combinedDateTime]; 

/* release the formatters */ 
[curDateFormatter release]; 
[timeFormatter release]; 
[combinedFormatter release]; 

return combinedDate; 

說,這是做它被張貼此消息時,它應該有11/10/2010 06:47而是它就像2009/12/27 11:45。在模擬器和設備中這樣做。

+1

什麼是可變時間intialized作爲? – 2010-11-10 12:03:13

+0

年度部分應該是「yyyy」而不是「YYYY」。 – Anna 2010-11-10 17:29:23

回答

1

除了使用combinedDateFormatter的,請嘗試以下操作:

NSDate *combinedDate = [NSDate dateWithNaturalLanguageString:combinedDateTime]; 

這對我工作的罰款。

價值combinedDateTime字符串是2011年9月27日11:55

價值combinedDate約會對象是2011-09-27 11:55:00 0530

相關問題