这几天写代码,遇到一个恶心的问题,日期老是报错,之后便拿出jdk源码撸了一遍,下面是详细的解读。
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Date date = new Date(2018, 1, 7);
System.out.println(date.toLocaleString());
}
}
这段代码的输出是
3918-2-7 0:00:00
当时我认为应该是 2018-02-07 的
随后翻看了jdk util.date包
看到了这句话
/* @param year the year minus 1900.
* @param month the month between 0-11.
* @param date the day of the month between 1-31.*/
@Deprecated
public Date(int year, int month, int date) {
this(year, month, date, 0, 0, 0);
}
随后我跟到了这里,一下子豁然开朗
@Deprecated
public Date(int year, int month, int date, int hrs, int min, int sec) {
int y = year + 1900;
// month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
if (month >= 12) {
y += month / 12;
month %= 12;
} else if (month < 0) {
y += CalendarUtils.floorDivide(month, 12);
month = CalendarUtils.mod(month, 12);
}
BaseCalendar cal = getCalendarSystem(y);
cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
getTimeImpl();
cdate = null;
}
date的年是以1900年为基础的,月是以0为基础,即0就是一月,日正常。
到这里,发现如果想要新建一个年月日的日期,就需要新建了。
例:Date date2 = new Date(2018-1900, 1-1, 7); //这样新建出来才是 2018年1月7日。