Java DateFormat 和 SimpleDateFormat 返回不正确的日期
今天是 2010 年 2 月 9 日星期二,当我打印日期时,我得到了错误的日期:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date today = formatter.parse(String.format("%04d-%02d-%02d",
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)));
System.out.println("Today is " + today.toString());
打印行结果为:“今天是 2010 年 1 月 9 日星期六 00:00:00 CST 2010”
这肯定不是 1 月 9 日星期六,而是2 月 9 日星期二。我假设我做错了什么,所以有人可以让我知道这里出了什么问题吗?我必须手动设置星期几吗?
更新 注意:我不想使用 new Date()
初始化今天,因为我希望将小时、分钟、秒和毫秒初始化为 0
。这是必要的,这样我就可以将用户输入的日期与今天进行比较:如果用户输入今天的日期并且我使用格式化程序构造一个 Date 对象,那么如果我使用 new Date()
初始化今天并且我比较两个日期 - 今天将晚于用户选择的日期(这是不正确的)。因此,我需要在今天开始时初始化,没有小时/分钟/秒/毫秒。
Today is Tuesday, February 9, 2010 and when I print the date I get the wrong date:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date today = formatter.parse(String.format("%04d-%02d-%02d",
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)));
System.out.println("Today is " + today.toString());
The print line results in: "Today is Sat Jan 09 00:00:00 CST 2010"
It most certainly is not Saturday Jan 09, it's Tuesday Feb 09. I'm assuming I'm doing something wrong, so can anybody let me know what's wrong here? Do I have to manually set the day of week?
Update
Note: I don't want to initialize today with new Date()
because I want the hours, minutes, seconds and milliseconds initialized to 0
. This is necessary so I can compare a user input date with today: if the user inputs today's date and I use the formatter to construct a Date object, then if I initialize today with new Date()
and I compare the two dates- today will be after the user selected date (which is incorrect). Thus I need to initialize today at the beginning of the day without the hr/min/sec/ms.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
令人困惑的是,日历月份从 0(一月)到 11(十二月)计数,因此当您从日历中提取 MONTH 字段时,您将“2010-01-09”传递给 formatter.parse() 。
在相关的SO问题中对此进行了讨论。
Confusingly, Calendar months count from 0 (January) to 11 (December), so you're passing "2010-01-09" to formatter.parse() when you extract the MONTH field from the Calendar.
There's a discussion of this in a related SO question.
如果您不想使用 JodaTime,您可以使用:
这比字符串格式化/解析方法更高效且更不易出错。
如果您可以使用 JodaTime,这是一个更推荐的方法:
If you don't want to use JodaTime you could use:
This is much more efficient and less error-prone than your String formatting/parsing approach.
If you can use JodaTime this is a much preferred method: