我有以下代码,用于获取一个 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。在模拟器和设备中执行此操作。
最佳答案
不要使用 combinedDateFormatter,请尝试以下操作:
NSDate *combinedDate = [NSDate dateWithNaturalLanguageString:combinedDateTime];
这对我来说效果很好。
combinedDateTime 字符串的值为 09/27/2011 11:55
combinedDate 日期对象的值为 2011-09-27 11:55:00 +0530
关于iphone - NSDateFormatter 没有返回正确的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4144148/