2010-11-10 115 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

相关问题