Fundamentals 6 min read

Why Your Year‑Week Logic Breaks at Year‑End and How ISO‑8601 Fixes It

A real‑world bug caused by incorrect year‑week calculation is explained, then the ISO‑8601 week‑based year definition and Java's LocalDate/WeekFields APIs are introduced to reliably compute the correct year and week for any date.

DeWu Technology
DeWu Technology
DeWu Technology
Why Your Year‑Week Logic Breaks at Year‑End and How ISO‑8601 Fixes It

Problem Scenario

On January 5, 2024 a product issue was reported: a feature launched in July 2023 mishandled cross‑year dates because the method used to obtain the "week's year" was wrong. The front‑end sent a date like 2024-12-30 and expected the back‑end to interpret it as Year 2025, Week 1, but the back‑end stored an incorrect year value, causing downstream data errors.

Similar inconsistencies appeared for the first few days of January, where the stored year field did not match the expected week‑based year.

ISO‑8601 Week Definition

The ISO‑8601 standard defines weeks in a way that ensures consistent cross‑system interpretation:

The first week of a year is the week containing the year's first Thursday. This week may start in the previous calendar year.

Weeks start on Monday and end on Sunday.

Consequently, week numbers run from 1 to 52 or 53. Whether a week belongs to the current year or the previous/next year depends on where the majority (four or more) of its days fall.

Week‑Based Year (WBY) in Java

Java 8 introduced java.time.LocalDate and java.time.temporal.WeekFields, which provide methods to obtain the week‑based year and week number according to ISO‑8601. Using these classes eliminates the need to rely on the calendar year ( getYear()) for week calculations.

Example usage (simplified):

LocalDate date = LocalDate.of(2024, 12, 30);
WeekFields wf = WeekFields.ISO;
int weekBasedYear = date.get(wf.weekBasedYear());
int weekOfYear = date.get(wf.weekOfWeekBasedYear());
// weekBasedYear == 2025, weekOfYear == 1

The article includes screenshots of the JDK 8 source implementation that extracts the week‑based year, illustrating the exact logic used internally.

Takeaway

When a business scenario requires "year‑week" values, always use the ISO‑8601 week‑based year together with the week number. Relying on the natural calendar year leads to subtle bugs, especially around year boundaries. Solid fundamentals in date‑time handling are essential for reliable backend systems.

backendJavaLocalDateiso-8601datetime-apiweek-based-year
DeWu Technology
Written by

DeWu Technology

A platform for sharing and discussing tech knowledge, guiding you toward the cloud of technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.