Android get difference days between two dates return wrong days

Viewed 70

I have 2 methods to get the difference of days between 2 dates. The first is:

public static int getDiffDays(Date dateOne, Date dateTwo){
        Long timeOne = dateOne.getTime();
        Long timeTwo = dateTwo.getTime();
        long diff = timeOne - timeTwo ;
        return (int) (diff / (24 * 60 * 60 * 1000));
    }

The other one is:

public static long getDiffTimeUnit(Date dateOne, Date dateTwo, TimeUnit unit){
        return unit.convert((dateOne.getTime() - dateTwo.getTime()), TimeUnit.MILLISECONDS);
    }

Both methods return me a wrong value when the dates have 1 day of difference, otherwise they return the right value. So for example with these 2 dates:

Mon Aug 01 00:00:00 GMT+02:00 2022 Tue Aug 02 00:00:00 GMT+02:00 2022

They return me 0 day of difference instead of 1...

But with these 2 dates:

Mon Aug 08 00:00:00 GMT+02:00 2022 Wed Aug 31 00:00:00 GMT+02:00 2022

They return me 23 days of difference that is correct.

How can I resolve this issue? (I cannot use ChronoUnit because it requires API 26)

Thank you

Example 1

Example 2

Example 3

Example 4

1 Answers

The code you shared getDiffDays is working fine.

You told us that

  • dateOne is "Tue Aug 02 00:00:00 GMT+02:00 2022"
  • dateTwo is "Mon Aug 01 00:00:00 GMT+02:00 2022".

However in the last screenshot,

  • dateOne has a timestamp of 1659391200000.
  • dateTwo has a timestamp of 1659304800196.

So, dateTwo is Aug 01 plus 196ms.

The difference between those days is 86399804. Nearly a day but not. 86399804 / 86400000 is 0 in integer's arithmetic. This is why you get 1 day short.

Here a piece of code for demo purposes.

long timestamp = 1659391200000L; // Tue Aug 02 00:00:00 GMT+02:00 2022
      
Date date_2Aug = new Date(timestamp);
Date date_2Aug_plus_196ms = new Date(timestamp + 196L);
            
System.out.println(date_2Aug); // output: Tue Aug 02 00:00:00 GMT+02:00 2022
System.out.println(date_2Aug_plus_196ms); // output: Tue Aug 02 00:00:00 GMT+02:00 2022

// let's see the date with milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSSZ");
String formattedDate2Aug = sdf.format(date_2Aug);
System.out.println(formattedDate2Aug); // output: 02/08/2022 00:00:00.000+0200

String formattedDate2Aug_plus_196ms = sdf.format(date_2Aug_plus_196ms);
System.out.println(formattedDate2Aug_plus_196ms); // output: 02/08/2022 00:00:00.196+0200

When you give a date "Mon Aug 01 00:00:00 GMT+02:00 2022", I expect a date with timestamp of 1659391200000.

This is why sharing a minimal test code is important. Screenshots may drive us to wrong conclusions.

Related