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 !
java.timesdf.parse(sdf.format(actualStep.getPlannedDate())), first lettingSimpleDateFormatformat aDateand then parse its result, is pretty cumbersome.SimpleDateFormat,CalendarandDate. Those classes were poorly designed, the first in particular notoriously troublesome, and all are long outdated. UseLocalDateandChronoUnit.DAYS, both from java.time, the modern Java date and time API.TimeUnitfalsely assumes that a day is always 24 hours. You may have observed that summer time (DST) went into effect in great parts of Europe yesterday, Sunday 26 March (also observable from the different time zone abbreviationsCETandCESTin your output). So that day was only 23 hours. So when measuring 7 days across that day you don’t get milliseconds enough for 7 * 24 hours, andTimeUnittruncates to 6 days instead of 7. When you add1L, you get 7 instead of the 8 you would normally get from the same operation.ChronoUnit.DAYS.between(LocalDate.parse("2023-03-21"), LocalDate.now(ZoneId.systemDefault())). I got the correct count;7. BecauseLocalDateis independent of time zone and thus cannot be affected by summer time and such time anomalies.