I wanted to implement a check before and after the hire date and the hire date, so I created a date object with GregorianCalendar (a concrete subclass of Calendar) as follows and compared it with compareTo.
dateCheck.java
Date march = new GregorianCalendar(2019,3,31).getTime(); //March 31, 2019(Day)
Date april = new GregorianCalendar(2019,4,1).getTime(); //April 01, 2019(Month)
System.out.println(march.compareTo(april)); //Execution result: 0
The return value of the compareTo method (comparing the time value represented by the two Calendar objects (offset in milliseconds from the epoch)) -Reference object <argument object → value less than 0 -Reference object> Argument object → Value greater than 0 -Reference object = argument object → 0
Since the number of milliseconds elapsed from the reference time is larger on April 1 than on March 31 (the date is later), it is desirable to return a value less than 0. ** But the result is 0 (same). ** **
Try to output two date objects to the console.
Wed May 01 00:00:00 JST 2019
Wed May 01 00:00:00 JST 2019
Both are Wednesday, May 1, 2019. I noticed "Ah" here.
I completely forgot this. In other words, the date is converted as ** March 31 → April 31 and April 1 → May 1 **. April 31st does not exist, but it seems that it will be judged only by the elapsed milliseconds without such a problem.
So, if you set the value minus 1 to the month, it will be converted properly as you want.
dateCheck.java
Date march = new GregorianCalendar(2019,2,31).getTime(); //Execution result: Sun Mar 31 00:00:00 JST 2019
Date april = new GregorianCalendar(2019,3,1).getTime(); //Execution result: Mon Apr 01 00:00:00 JST 2019
System.out.println(march.compareTo(april)); //Execution result:-1
By the way, if you look at the Reference, Calendar will use * when interpreting calendar fields. * It seems to use two modes, strict and non-strict **.
Strict mode: Calendar throws an exception if there is a mismatch in the calendar field Non-strict mode: Calendar accepts a wider range of calendar field values than it generates itself
By default, it is in non-strict mode, but if you change to strict mode and set a date outside the range, it will not accept April 31st.
dateCheck.java
Calendar march = new GregorianCalendar();
Calendar april = new GregorianCalendar();
april.setLenient(false); //Switch to strict mode
march.setWeekDate(2019,3,31); //success
april.setWeekDate(2019,3,31); //Failure: java.lang.IllegalArgumentException: invalid dayOfWeek: 31
As mentioned above, it is very embarrassing, but it may be a super super beginner. I leave it in my mind.
Recommended Posts