Days between two dates throws
A medium Java puzzle in the dates, time zones and dst family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
Duration works with time-based amounts and requires a time component. A LocalDate has none, so Duration.between throws UnsupportedTemporalTypeException: Unsupported unit: Seconds.
The fix
How to avoid it next time
Use ChronoUnit.DAYS.between for day counts and Period for years-months-days differences.
Want the background? Read java.time dates and times in the Java concepts library.
About dates, time zones and dst
Local dates and times hide the zone they belong to. Daylight saving changes the length of a day, a month has varying lengths and the week-year differs from the calendar year around New Year.
In code review: Ask which zone each date is in and whether the code uses an instant or a local time. Prefer java.time with an explicit ZoneId over Date and SimpleDateFormat.
More puzzles in this family
Frequently asked questions
What is the bug in "Days between two dates throws"?
Duration works with time-based amounts and requires a time component. A LocalDate has none, so Duration.between throws UnsupportedTemporalTypeException: Unsupported unit: Seconds. The faulty line is line 7: long days = Duration.between(from, to).toDays();
How do I fix it?
Replace it with: long days = java.time.temporal.ChronoUnit.DAYS.between(from, to);. Use ChronoUnit.DAYS.between for day counts and Period for years-months-days differences.
How do I catch dates, time zones and dst in code review?
Ask which zone each date is in and whether the code uses an instant or a local time. Prefer java.time with an explicit ZoneId over Date and SimpleDateFormat.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.