You can create a date and set it on the first day of the week during the first week of the year with the following:
int year = 2016; WeekFields weekFields = WeekFields.ISO; LocalDate date = LocalDate.now().with(weekFields.weekBasedYear(), year) .with(weekFields.weekOfWeekBasedYear(), 1) .with(ChronoField.DAY_OF_WEEK, 1);
Thanks to JodaStephen's comment, another way would be to use IsoFields
.
LocalDate date = LocalDate.now().with(IsoFields.WEEK_BASED_YEAR, year) .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 1) .with(ChronoField.DAY_OF_WEEK, 1);
WeekFields.ISO
presents the ISO definition of the week:
The definition of ISO-8601, where a week starts on Monday and in the first week, is at least 4 days.
The ISO-8601 standard defines a calendar system based on weeks. It uses the concepts of weekly and weekly weeks to separate the number of days, rather than the standard year / month / day.
Please note that the first week may begin in the previous calendar year. Also note that the first few days of a calendar year may be in the weekly year corresponding to the previous calendar year.
From this definition you can get:
weekBasedYear()
represents the weekly weekly field:
This is a concept of the year in which weeks start on a fixed day of the week, for example, on Monday and every week - exactly one year.
In this case, we want to set it in the desired year.
weekOfWeekBasedYear()
represents the week of the week by year
This is the concept of counting weeks during the year when weeks start on a fixed day of the week, for example, on Monday and each week is exactly one year.
In this case, we want the first week of the week to weeks, so we set it to 1.
ChronoField.DAY_OF_WEEK
, which represents the day of the week. In this case, we want the first day of the week to be set to 1.
Then, with that date, you can really LocalDate.plusWeeks(1)
over all the weeks of the year by calling LocalDate.plusWeeks(1)
. The question is how many times do you need to iterate? It can be more than 52 weeks a year. There are 52 or 53 weeks per week-year. A.
You can get the number of weeks with the following. This call to rangeRefinedBy(date)
to get valid weekday field values ββfor a given date and get the maximum value.
long maxWeekOfYear = weekFields.weekOfWeekBasedYear().rangeRefinedBy(date).getMaximum();