Difference in days between two dates in Java?

后端 未结 19 1966
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 08:26

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

  int age=calculateDiffer         


        
19条回答
  •  Happy的楠姐
    2020-11-22 08:59

    Illustration of the problem: (My code is computing delta in weeks, but same issue applies with delta in days)

    Here is a very reasonable-looking implementation:

    public static final long MILLIS_PER_WEEK = 7L * 24L * 60L * 60L * 1000L;
    
    static public int getDeltaInWeeks(Date latterDate, Date earlierDate) {
        long deltaInMillis = latterDate.getTime() - earlierDate.getTime();
        int deltaInWeeks = (int)(deltaInMillis / MILLIS_PER_WEEK);
        return deltaInWeeks; 
    }
    

    But this test will fail:

    public void testGetDeltaInWeeks() {
        delta = AggregatedData.getDeltaInWeeks(dateMar09, dateFeb23);
        assertEquals("weeks between Feb23 and Mar09", 2, delta);
    }
    

    The reason is:

    Mon Mar 09 00:00:00 EDT 2009 = 1,236,571,200,000
    Mon Feb 23 00:00:00 EST 2009 = 1,235,365,200,000
    MillisPerWeek = 604,800,000
    Thus,
    (Mar09 - Feb23) / MillisPerWeek =
    1,206,000,000 / 604,800,000 = 1.994...

    but anyone looking at a calendar would agree that the answer is 2.

提交回复
热议问题