How can I iterate over every week in a year in Java 8?

Viewed 2241

Apologies in advance if I confuse any ISO date related terms here.

I would like to be able to iterate over every week in a given year (say, 2015). I realize that you can calculate the number of weeks between 1/1/2015 and 12/31/2015, but that doesn't conform to the ISO standard of a week. Rather, it gives the number of 7 day periods between two dates. The first ISO week of the year doesn't necessarily start on 1/1/2015.

If I can get the first date of the first week, I believe I can simply iterate via ZonedDateTime.plusWeeks(1) for 52 weeks. You can get the week number of an arbitrary date via the field accessor:

ZonedDateTime date = ZonedDateTime.now();
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int weekNumber = date.get(weekFields.weekOfWeekBasedYear());

Given this, I think it must be possible to get the date of the first day of the first week of a specific year in the Java8 Time API, but I have not found a way to do it yet.

1 Answers
Related