How to get dates of a week (I know week number)?

I know the week number of the year, a week is start from Sunday, then Monday, Tuesday...,Saturday.

Since I know the week number, what's the efficient way to get the dates of the specific week by using Java code??


Solution 1:

If you don't want external library, just use calendar.

SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);        
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(sdf.format(cal.getTime()));    

Solution 2:

Pure Java 8 / java.time solution

Based on this:

final long calendarWeek = 34;
LocalDate desiredDate = LocalDate.now()
            .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, calendarWeek)
            .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

Solution 3:

You can use the joda time library

int weekNumber = 10;
DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekNumber);
DateTime weekEndDate = new DateTime().withWeekOfWeekyear(weekNumber + 1);

Solution 4:

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution:

The first step is to find the first day of the week and as the second step, we just need to iterate all the seven days starting with this date.

Note that the first day of the week is Locale-dependent e.g. it is Monday in the UK while Sunday in the US. As per the ISO 8601 standards, it is Monday. For comparison, check the US calendar and the UK calendar.

Demo of the first step:

import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.WeekFields;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Test
        int weekNumber = 34;
        System.out.println(getFirstDayOfWeek(weekNumber, Locale.UK));
        System.out.println(getFirstDayOfWeek(weekNumber, Locale.US));
    }

    static LocalDate getFirstDayOfWeek(int weekNumber, Locale locale) {
        return LocalDate
                .of(Year.now().getValue(), 2, 1)
                .with(WeekFields.of(locale).getFirstDayOfWeek())
                .with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
    }
}

Output:

2021-08-23
2021-08-15

ONLINE DEMO

Demo of the second step:

import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.WeekFields;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        // Test
        getAllDaysOfTheWeek(34, Locale.US).forEach(System.out::println);
    }

    static LocalDate getFirstDayOfWeek(int weekNumber, Locale locale) {
        return LocalDate
                .of(Year.now().getValue(), 2, 1)
                .with(WeekFields.of(locale).getFirstDayOfWeek())
                .with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
    }

    static List<LocalDate> getAllDaysOfTheWeek(int weekNumber, Locale locale) {
        LocalDate firstDayOfWeek = getFirstDayOfWeek(weekNumber, locale);
        return IntStream
                .rangeClosed(0, 6)
                .mapToObj(i -> firstDayOfWeek.plusDays(i))
                .collect(Collectors.toList());
    }
}

Output:

2021-08-15
2021-08-16
2021-08-17
2021-08-18
2021-08-19
2021-08-20
2021-08-21

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.