Search code examples
javadatesimpledateformat

Issue when comparing date with Java


I am encountering some issues right now when I compare two dates in Java.

I want to check that a date is the same day on the next week that today.

First, I am doing this:

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

        Calendar todayCalendar = Calendar.getInstance();
        Date today = sdf.parse(sdf.format(todayCalendar.getTime()));

        Step step = actualStep.getStep();
        Date plannedDate = sdf.parse(sdf.format(actualStep.getPlannedDate()));

        long diffInMillies = Math.abs(today.getTime() - plannedDate.getTime());
        long deltaDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS) +1L;

When I check the different values, I get this:

Mon Mar 27 00:00:00 CEST 2023
Mon Mar 20 00:00:00 CET 2023
deltaDays: 7

So I do get a difference of 7 days this way. The thing is I do not get the same when I'm trying to do some unit tests:

        Calendar todayCalendar = Calendar.getInstance();
        Date today = todayCalendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Integer day = 7;
        todayCalendar.add(Calendar.DAY_OF_WEEK, +day);
        Date expectedReminderDay = sdf.parse(sdf.format(todayCalendar.getTime()));

This time, I get:

Mon Mar 27 00:00:00 CEST 2023
Mon Apr 03 00:00:00 CEST 2023
deltaDays: 8

Does anyone know why, in one case, I get 8 days of difference and 7 in another while having a week apart ?

Thanks for reading !


Solution

  • It's the +1L in

    long deltaDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS) +1L;
    

    That makes 7 into 8. Actually not the current reading is the one you should look at, but the prior one you tried to fix: originally you had 6 because of the CET-CEST change. As clock jumped an hour, there're 6 days and 23 hours between 20th of March 00:00 CET and 27th of March 00:00 CEST, then the difference got rounded downwards, to 6 days.