Introduction

In this tutorial, we'll show you how to convert week in year to date in Java. We'll extract the date of the first and last day of the week where we have provided the number of a week in a year. You'll notice that we're using  WeekFields class, which is of great help when dealing with temporal data related to weeks. WeekFields class provides five fields that give us access to the value of any temporal object:

  • dayOfWeek() 
  • weekOfMonth()
  • weekOfYear()
  • weekOfWeekBasedYear()
  • weekBasedYear()

Implementation

import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;

public class ConvertWeekToDate {

	public static void main(String[] arguments) {
		int weekInYear = 19;
		WeekFields weekFields = WeekFields.of(Locale.getDefault());
		LocalDate dateStart = LocalDate.now().with(weekFields.weekOfYear(), weekInYear).with(weekFields.dayOfWeek(), 1);
		LocalDate dateEnd = dateStart.plusDays(7);
		System.out.println(dateStart);
		System.out.println(dateEnd);
	}
}

In this example, we picked week 19. Also, you'll notice that we used the current year through LocalDate.now(). If you want to be able to provide a specific year (in this example 1945), you can use:

LocalDate dateStart = LocalDate.ofYearDay(1945, 1)
.with(weekFields.weekOfYear(), weekInYear)
.with(weekFields.dayOfWeek(), 1);

Check out our other tutorials:

The ultimate Spring Boot Rest API beginners guide

Create and download jasper report PDF via REST service in Spring Boot