iphone - NSDateFormatter 没有返回正确的日期

标签 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。在模拟器和设备中执行此操作。

最佳答案

不要使用 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/

相关文章:

ios - 从 iPhone 安全地发送帖子数据

iphone - 按钮圆角上的 UIImage

objective-c - 何时将平移手势的结果保存到 NSUserDefaults

ios - 如何使用 xib 文件在单元格中 rtl UITextField?

ios - 如何更改表格 View 单元格文本?

objective-c - 在使用额外行插入新记录的同时在编辑模式之间切换时如何使用核心数据并正确显示动画?

ios - 为什么使用 CGImageRef 而不是 CGImage 来代替?

ios - UISearchBar 背景外观

iphone - 如何处理只读属性的内存

ios - 运行一个循环直到 UIPanGestureRecognizer 结束