How to calculate the days belonging to an ISO based week number

Tom :

I have an ISO based week number that is calculated using the following Java 8 LocalDate API

int weekNumOfYear = LocalDate#get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)

Given the year, and the week number (eg, 201927),How could I calculate the start day and end day for this week(201917)?

I am Using Calendar class for this problem, but not sure it is correct(especially, whether is has followed the ISO format)

Update: The following code doesn't work correctly for 201953, there is no 53th week for 2019

@Test
    public void testGetWeekDays() {
        Integer year = 2019;
        Integer week = 27;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();

        //Use ISO format
        cal.setMinimalDaysInFirstWeek(4);

        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, week);
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        String beginDate = sdf.format(cal.getTime());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        String endDate = sdf.format(cal.getTime());
        System.out.println(beginDate);
        System.out.println(endDate);
    }
Deadpool :

You can also use with to get start day and end day of week

System.out.println(localDate.with(DayOfWeek.MONDAY));
System.out.println(localDate.with(DayOfWeek.SUNDAY));

If you want to get start day and end day from week number, then use ISO_WEEK_DATE

LocalDate startDay = LocalDate.parse("2019-W26-1", DateTimeFormatter.ISO_WEEK_DATE);

LocalDate endDay = LocalDate.parse("2019-W26-7", DateTimeFormatter.ISO_WEEK_DATE);

One digit for the day-of-week. The value run from Monday (1) to Sunday (7).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328382&siteId=1