Getting the Date from a Week Number in Java

When I started to publish week notes to my site through my Micropub server, I wanted to programmatically set up the metadata for a post, which looks like:

title: "Week Notes 21#49"
description: "What happened in the week of 2021-12-06?"

In this case, we need the short year name, the week number, and the ISO8601 date for the Monday of that week.

Looking around for a way to do this in Java, I found that we can use IsoFields in conjunction with LocalDate to create the date, for instance:

int year = 2020;
int week = 53;
LocalDate desiredDate =
  LocalDate.now()
  .withYear(year)
  // this doesn't work
  .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, week):

System.out.println(desiredDate);

Fortunately this StackOverflow answer highlights that we can use TemporalAdjusters.previousOrSame to pick up the Monday of the week, like so:

int year = 2020;
int week = 53;
LocalDate desiredDate =
  LocalDate.now()
  .withYear(year)
  .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, week)
  .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

System.out.println(desiredDate);

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

This blog post is 100% human-written, and has nothing derived from LLMs (be it code, editorial support or prose).

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.