NSDateFormatter未返回正确的日期

时间:2010-11-10 11:48:47

标签: iphone objective-c ios nsdate nsdateformatter

我有以下代码,用于占用一个NSDate的时间和当前日期,并将它们组合成一个NSDate。但是格式化程序设置正确,但它返回的日期甚至不应该接近应该的日期。这是代码

/* 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但是它就像12/27/2009 11:45。这是在模拟器和设备中。

2 个答案:

答案 0 :(得分:1)

请尝试以下方法,而不是使用combinedDateFormatter:

    NSDate *combinedDate = [NSDate dateWithNaturalLanguageString:combinedDateTime];

这对我来说很好。

combinedDateTime字符串的值是09/27/2011 11:55

combinedDate date对象的值是2011-09-27 11:55:00 +0530

答案 1 :(得分:0)