Java – The instant time of the week of the year

The instant time of the week of the year… here is a solution to the problem.

The instant time of the week of the year

I need instant time from the first week of the year. Now I use the old Calendar API to calculate the time:

int week = 1;  week of year
final Calendar cal = new GregorianCalendar();
cal.set(0, 1, 0, 0, 0, 0);  reset calendar
cal.set(Calendar.YEAR, Year.now().getValue());
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
final Instant start = cal.getTime().toInstant();
final Instant end = start.plus(Period.ofWeeks(1));

Is it possible to get Instant from one week of the year using the new Java Time API (java.time package)?

Solution

    WeekFields wf = WeekFields.of(Locale.getDefault());

int week = 1;  week of year

LocalDate startDate = LocalDate.now(ZoneOffset.UTC)
            .with(wf.weekOfWeekBasedYear(), week)
            .with(wf.dayOfWeek(), 1);
    Instant startInstant = startDate.atStartOfDay(ZoneOffset.UTC).toInstant();
    LocalDate endDate = startDate.plusWeeks(1);
    Instant endInstant = endDate.atStartOfDay(ZoneOffset.UTC).toInstant();

System.out.println("" + startInstant + " - " + endInstant);

My locale uses ISO weeks. The output here is:

2019-12-29T00:00:00Z – 2020-01-05T00:00:00Z

If you want an ISO week independent of the locale, set wf to WeekFields.ISO. If you want a different week numbering scheme, set WF accordingly.

To prevent other readers from wondering, Kirill defines the weekend as the first moment of the following week. This is recommended. It is called using half-open intervals for time intervals.

I also agree with the issue that obviously using java.time for this task should be preferred over Calendar. Calendar is poorly designed and outdated, and I believe the code using java.time is easier to read.

Also, the code that uses Calendar in question doesn’t set the date to the first day of the week, so it won’t give you that day. Although I haven’t tested it, I suspect that the code sometimes produces unexpected results around the New Year.

My code using WeekFields from java.time will remain in the current week-based year, which is different from the calendar year. For example, if I run it on December 30, 2019, it will still give Week 1 of MED 2020 because we are already in that week.

Related Problems and Solutions