NSDate dateFromString 2 个月错了吗? [英] NSDate dateFromString 2 months wrong?

查看:34
本文介绍了NSDate dateFromString 2 个月错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
[dateFormater setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
[dateFormater setLocale:[NSLocale currentLocale]];
[dateFormater setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *localDate = [dateFormater dateFromString:localUpdate];
NSDate *serverDate = [dateFormater dateFromString:serverUpdate];

localUpdate 和 serverUpdate 的输入字符串是:

The input strings for localUpdate and serverUpdate are:

2014-01-31 23:42:17
2014-02-01 00:09:37

当把它们从 NSString 转换为 NSDate 时,第二个是 2 个月后?

When converting those from NSString to NSDate, the second one is 2 months behind?

2014-01-31 22:42:17 +0000
2013-12-31 23:09:37 +0000

谁能解释一下?

推荐答案

检查这一行:

[dateFormater setDateFormat:@"yyyy-MM-DD HH:mm:ss"];

正确的日期格式是@"yyyy-MM-dd HH:mm:ss" 带有 "dd" 而不是 "DD"

the correct date format is @"yyyy-MM-dd HH:mm:ss" with "dd" not "DD"

我曾经遇到过同样的问题...如果日期格式不正确,当您使用 dateFormatter 时,它会将日期减去或增加一个月.

I had the same problem once... and if the date format it's incorrect, when you use the dateFormatter, it will subtract or add one month to the date.

这篇关于NSDate dateFromString 2 个月错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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