4
LocalDate initial = LocalDate.now();
DayOfWeek dayOfWeek = DayOfWeek.WEDNESDAY;
WeekFields weekFields = WeekFields.of(dayOfWeek, 1);
int weekNo = date.get(weekFields.weekOfWeekBasedYear());
System.out.println("Week No"+weekNo);

I am using the above code for date 2018-07-29. I expect week no 30, but I get 31.

What am I missing here to get the result of 30?

Tomasz Linkowski
  • 4,386
  • 23
  • 38
Mahendra
  • 3,647
  • 2
  • 16
  • 16

1 Answers1

3

If you expected output as according to ISO-8601, where current week is week 30, you'd need to follow this:

Week number according to the ISO-8601 standard, weeks starting on Monday. The first week of the year is the week that contains that year's first Thursday (='First 4-day week').

This is implemented by WeekFields.ISO.

If instead, you want the week to start on WEDNESDAY, you only need to change the minimalDaysInFirstWeek from 1 to 4 (='First 4-day week'):

LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(DayOfWeek.WEDNESDAY, 4);
int weekNo = date.get(weekFields.weekOfWeekBasedYear());
System.out.println("Week No " + weekNo);
Tomasz Linkowski
  • 4,386
  • 23
  • 38