java 48 lines · 5 steps

A custom ISO-week Converter in Spring

A small immutable value type plus a registered Spring Converter that turns strings like 2024-W07 into a typed week.

Explained by highlit
1package com.example.web.convert;
2 
3import java.time.LocalDate;
4import java.time.format.DateTimeFormatter;
5import java.util.Locale;
6 
7import org.springframework.core.convert.converter.Converter;
8import org.springframework.format.Formatter;
9import org.springframework.lang.NonNull;
10import org.springframework.stereotype.Component;
11 
12public final class IsoWeek {
13 
14 private final LocalDate monday;
15 
16 private IsoWeek(LocalDate monday) {
17 this.monday = monday;
18 }
19 
20 public LocalDate getMonday() {
21 return monday;
22 }
23 
24 public LocalDate getSunday() {
25 return monday.plusDays(6);
26 }
27 
28 static IsoWeek parse(String value) {
29 String[] parts = value.split("-W");
30 if (parts.length != 2) {
31 throw new IllegalArgumentException("Expected format yyyy-Www, got: " + value);
32 }
33 int year = Integer.parseInt(parts[0]);
34 int week = Integer.parseInt(parts[1]);
35 LocalDate monday = LocalDate.ofYearDay(year, 1)
36 .with(java.time.temporal.WeekFields.ISO.weekOfWeekBasedYear(), week)
37 .with(java.time.temporal.WeekFields.ISO.dayOfWeek(), 1);
38 return new IsoWeek(monday);
39 }
40 
41 @Component
42 public static class StringToIsoWeekConverter implements Converter<String, IsoWeek> {
43 @Override
44 public IsoWeek convert(@NonNull String source) {
45 return IsoWeek.parse(source.trim());
46 }
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Modeling a domain concept as an immutable value type keeps parsing and derived data in one trustworthy place.
  2. 2Implementing Spring's Converter interface lets the framework map request strings to rich types automatically.
  3. 3Annotating a converter with @Component registers it in Spring's conversion service without manual wiring.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A custom ISO-week Converter in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code