BackendBench
Coffee
Spot the Bug #78

Forty-one days that count as eleven

A hard 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.

hardDates, time zones and DSTbuggy line: 8

Highlighted: line 8. Play this one as a puzzle without the answer.

What is wrong

Period.getDays returns only the days component of "1 month and 10 days", which is 10, not the total of 41 days. Period is a calendar amount split into years, months and days.

The fix

System.out.println("Days: " + java.time.temporal.ChronoUnit.DAYS.between(start, end));

How to avoid it next time

Use ChronoUnit.DAYS.between for a total day count and keep Period for human readable 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

๐Ÿž Play today's puzzleAll 132 bugsโ† #77#79 โ†’

Frequently asked questions

What is the bug in "Forty-one days that count as eleven"?

Period.getDays returns only the days component of "1 month and 10 days", which is 10, not the total of 41 days. Period is a calendar amount split into years, months and days. The faulty line is line 8: System.out.println("Days: " + p.getDays());

How do I fix it?

Replace it with: System.out.println("Days: " + java.time.temporal.ChronoUnit.DAYS.between(start, end));. Use ChronoUnit.DAYS.between for a total day count and keep Period for human readable 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.

More tools you might need