NSDateFormatter 使用 stringWithDate 中的字符串输出错误: [英] NSDateFormatter wrong output with string from stringWithDate:

查看:42
本文介绍了NSDateFormatter 使用 stringWithDate 中的字符串输出错误:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 NSDateFormatter 会误解他自己创建的 dateString?

Why does NSDateFormatter misinterpretes his own created dateString?

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

 [dateFormatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:ss.SSSZZZZ"];

 NSDate *now = [NSDate date];

 NSLog(@"Now: %@, Date: %@", [dateFormatter dateFromString:[dateFormatter stringFromDate:now]], now);

产生以下结果:现在:1970-01-06 18:07:05 +0100,日期:2010-01-06 18:07:05 +0100

produces the following result: Now: 1970-01-06 18:07:05 +0100, Date: 2010-01-06 18:07:05 +0100

我知道您应该使用 yyyy 和 dd(而 yyyy 和 dd 不会发生这种情况),但这不是重点.我希望在解析格式化程序为我创建的字符串时收到相同的日期.

I know that you should use yyyy and dd (and it does not happen with yyyy and dd), but that's not the point here. I am expecting to receive the same date when parsing the string the formatter has created for me.

推荐答案

这行得通

[dateFormatter setDateFormat:@"y-MM-DD'T'HH:mm:ss.SSSZZZZ"];

看这里,http://www.crystalminds.nl/?p=4 有关不同标志的更多信息.

Look here, http://www.crystalminds.nl/?p=4 for more info about the difrent flags.

使用 YYYY 时,格式化程序似乎无法识别任何年份,因为

It seems like the formatter doesn't recognize any year when using YYYY because

[dateFormatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:ss.SSSZZZZ"];
// is equal to
[dateFormatter setDateFormat:@"MM-DD'T'HH:mm:ss.SSSZZZZ"];

这篇关于NSDateFormatter 使用 stringWithDate 中的字符串输出错误:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆