Java – why is the difference between specific dates (03 / 12 / 2018) not the exact number of days?

I'm facing a strange problem with Java (versions 6, 7, 8) In this code, I try to calculate the date difference between two dates. This code gives my date difference between 03 / 12 / 2018 and 01 / 04 / 2018, which is 66.958 days instead of 67 days, which is a little surprising I haven't seen such behavior yet

To prove this theory, you can try any date before 03 / 11 / 2018, which is simple mathematics Please let us know what you think I've tried the chrononunit class bundled with Java, which correctly calculates the number of days, but I just want to know what happens here if you have any comments

static  void dateLogic1() throws ParseException{
       String matYear1 = "03/11/2018";
       String matYear2 = "03/12/2018";

       String stlDate = "01/04/2018";


       java.util.Date mtYear1 = new SimpleDateFormat("MM/dd/yyyy").parse(matYear1);
       java.util.Date mtYear2 = new SimpleDateFormat("MM/dd/yyyy").parse(matYear2);


       java.util.Date stYear = new SimpleDateFormat("MM/dd/yyyy").parse(stlDate);

       long time1 = mtYear1.getTime();
       long time2 = mtYear2.getTime();
       long time4 = stYear.getTime();


       double diff1 =  (double) (mtYear1.getTime()-stYear.getTime()) /( 24 * 60 * 60 * 1000);
       double diff2 =  (double) (mtYear2.getTime()-stYear.getTime()) /( 24 * 60 * 60 * 1000);

       System.out.println("Date Diff between "+ mtYear1 +" & "+ stYear +" is " + diff1 );
       System.out.println("Date Diff between "+ mtYear2  +" & "+ stYear +" is " + diff2 );

   }

Solution

It is related to daylight saving time At 2 a.m. on March 11, 2018, an hour was lost in many places If the hour is converted into a small part of the day (1 / 24), the result is a difference between 67 and 66.958

Edit: date Gettime() returns the number of milliseconds since 00:00:00 GMT, January 1, 1970, represented by the date object Because you lose one thousandth of an hour, that's the way fractional hours are lost

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>