java.util.Date到java.sql.Date转换错误的月份 [英] java.util.Date to java.sql.Date conversion gives wrong month
问题描述
考虑以下代码段:
Calendar futureDate = Calendar.getInstance();
int year = 2011;
int month = 11;
int day = 14;
futureDate.set(year,month, day);
System.out.println(futureDate.toString());
java.sql.Date sqlDate = new java.sql.Date( futureDate.getTime().getTime());
来自futureDate.toString()的打印输出是:
The printout from futureDate.toString() is:
..... YEAR = 2011,MONTH = 11,WEEK_OF_YEAR = 43,WEEK_OF_MONTH = 4,DAY_OF_MONTH = 14,DAY_OF_YEAR = 289,DAY_OF_WEEK = 1,DAY_OF_WEEK_IN_MONTH = 3,AM_PM = 0,HOUR = 11,HOUR_OF_DAY = 11,MINUTE = 32,SECOND = 51,MILLISECOND = 117,ZONE_OFFSET = -18000000,DST_OFFSET = 3600000]
.....YEAR=2011,MONTH=11,WEEK_OF_YEAR=43,WEEK_OF_MONTH=4,DAY_OF_MONTH=14,DAY_OF_YEAR=289,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=32,SECOND=51,MILLISECOND=117,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
显示Calendare对象持有正确的日期。但是,在转换为sql date并存储在数据库(MySQL通过JDBC)中之后,MySQL表显示2011-12-14,而不是2011-11-14。
我会怀疑区域设置和时区,但这些会导致日期不一致的日期不一致。
which shows that the Calendare object holds the correct date. However, after converting to sql date and storing in the database (MySQL through JDBC), the MySQL table shows '2011-12-14' for this date instead of '2011-11-14'. I would have suspected locale and time zone, but these would cause discrepancy in the time of day not in the month part of the date.
任何线索我做错了什么?
Any clues to what I did wrong?
推荐答案
Calendar#set(int,int,int)
将月份参数解释为零,因此 futureDate.set(2011,11,14)
将日历的月份设置为12月。
Calendar#set(int, int, int)
interprets the month argument as zero-based, so futureDate.set(2011, 11, 14)
sets the calendar's month to December.
这篇关于java.util.Date到java.sql.Date转换错误的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!