bashoogzaad bashoogzaad - 3 months ago 19
Java Question

Get LocalDateTime based on year and week of year

I have two integers:

year
and
week
. I would like to construct a
LocalDateTime
from these two values, where the date represents the first day of the particular week in the particular year.

I already tried this:

LocalDateTime ldt = LocalDateTime.of(year, 1, 1, 0, 0).plusWeeks(week-1);


This does not give the correct result, because the first day of the year is not always the beginning of the first week of that year. I can not seem to figure out how to get the first day of the first week either.

Is there any simple way to do this with the Date and Time API in Java 8?

Note: I know I could also create a workaround with answers given here, but this seems to far-fetched. Maybe it isn't, if so, let me know!

Answer

The following code will get a LocalDateTime and set it to the first day of the given week-of-year for the given year:

int week = 1;
int year = 2016;
WeekFields weekFields = WeekFields.of(Locale.getDefault());
LocalDateTime ldt = LocalDateTime.now()
                            .withYear(year)
                            .with(weekFields.weekOfYear(), week)
                            .with(weekFields.dayOfWeek(), 1);
System.out.println(ldt);

Note that the notion of week-of-year is locale specific. Here, I used the default Locale but you might need to use a user-provided locale.

If you want to get rid of the time part, you can add a call to truncatedTo(ChronoUnit.DAYS).

Comments