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);