月光宝盒花絮

“曾经有一份真诚的爱情摆在我的面前,但是我没有珍惜,等到了失去的时候才后悔莫及,尘世间最痛苦的事莫过于此。如果可以给我一个机会再来一次的话,我会跟那个女孩子说我爱她,如果非要把这份爱加上一个期限,我希望是一万年!”---大话西游之仙履奇缘

复制代码
    public static void main(String[] args) {         Date date=new Date(2018,12,31,0,0,0);                 System.out.println(date.getYear());         System.out.println(date.getMonth());         System.out.println(date.getDay());     }
复制代码

 

我们想打印出的结果是

2018

12

31

可是,运行后的结果打印

2019

0

5

穿越了吗?还是我的机器有问题?

月光宝盒之时间魔法--java时间的前生今世

 

换了别的机器依然如此。代码是不会骗人的,只好进源码看看

复制代码
 /**  * Allocates a <code>Date</code> object and initializes it so that  * it represents the instant at the start of the minute specified by  * the <code>year</code>, <code>month</code>, <code>date</code>,  * <code>hrs</code>, and <code>min</code> arguments, in the local  * time zone.  *  * @param year the year minus 1900.  * @param month the month between 0-11.  * @param date the day of the month between 1-31.  * @param hrs the hours between 0-23.  * @param min the minutes between 0-59.  * @see java.util.Calendar  * @deprecated As of JDK version 1.1,  * replaced by <code>Calendar.set(year + 1900, month, date,  * hrs, min)</code> or <code>GregorianCalendar(year + 1900,  * month, date, hrs, min)</code>.  */  @Deprecated  public Date(int year, int month, int date, int hrs, int min) {  this(year, month, date, hrs, min, 0);  }
复制代码

 

程序大揭秘

  1. 设置年份是从1900开始的,即2018-1900=118
  2. 设置月份是从0开始的,即0~11,12等于下一年119年的第一个月即值为0
  3. day返回的是是周几
复制代码
 /**  * Returns the day of the week represented by this date. The  * returned value (<tt>0</tt> = Sunday, <tt>1</tt> = Monday,  * <tt>2</tt> = Tuesday, <tt>3</tt> = Wednesday, <tt>4</tt> =  * Thursday, <tt>5</tt> = Friday, <tt>6</tt> = Saturday)  * represents the day of the week that contains or begins with  * the instant in time represented by this <tt>Date</tt> object,  * as interpreted in the local time zone.  *  * @return the day of the week represented by this date.  * @see java.util.Calendar  * @deprecated As of JDK version 1.1,  * replaced by <code>Calendar.get(Calendar.DAY_OF_WEEK)</code>.  */  @Deprecated  public int getDay() {  return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;  }
复制代码

 

java时间前生之Calenar

在1.1 版中,Calendar 类被添加到了Java 平台中,以矫正Date的缺点,由此大部分的Date 方法就都被弃用了。遗憾的是,这么做只能使情况更糟。我们的程序说明Date 和Calendar API 有许多问题。

复制代码
    public static void