Search code examples
javadatedate-arithmetic

Difference Between two dates in minutes - different months - Java


I want to find the difference in minutes between 2 dates. My code works well if the 2 dates are in the same month(and year) but it seems like the difference considers every month to be 31 days long so for the dates:

 2016-02-29 12:21
 2016-03-1 12:21

I get 4320 minutes or 72 hours

for:

 2016-04-30 12:21
 2016-05-01 12:21

I get 2880 minutes or 48 hours

my code where d1 and d2 are Date objects:

long getDateDiff(Date d1, Date d2, TimeUnit timeUnit) {
    long diff = d2.getTime() - d1.getTime(); //in millisec
    long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
    return diffMinutes;
}

Solution

  • Your result is very weird with me. So I tried it:

        @Test
    public void differenceDateTest() throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Date date = dateFormat.parse("2016-02-29 12:21");
        Date date2 = dateFormat.parse("2016-03-01 12:21");
        System.out.println(date2.getTime() - date.getTime());
        long mili = date2.getTime() - date.getTime();
        System.out.println(TimeUnit.MILLISECONDS.toHours(mili)); // 24 hours.
    }
    

    it returned exactly 24 hours.