24

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??

Mellon
  • 37,586
  • 78
  • 186
  • 264
  • do you mean, given it is the 22nd week of 2010, what is the date of that first day of the week (with the week's first day being Sunday) – nonopolarity Oct 15 '10 at 11:20

7 Answers7

46

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()));    
bungrudi
  • 1,417
  • 1
  • 17
  • 24
  • 4
    FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 20 '19 at 20:56
37

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));
Community
  • 1
  • 1
Mateusz Szulc
  • 1,734
  • 19
  • 18
  • 11
    If you want to get by week of another year yo could use `LocalDate.ofYearDay(year, 50)` instead of `LocalDate.now()`. DayOfYear (`50` in my case) can be random but should be not earlier than the number of the first day `DayOfWeek.MONDAY` in that year. – Alex78191 May 17 '17 at 13:05
11

You can use the joda time library

int weekNumber = 10;
DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekNumber);
DateTime weekEndDate = new DateTime().withWeekOfWeekyear(weekNumber + 1);
Alois Cochard
  • 9,812
  • 2
  • 29
  • 30
  • This will not work if last week of year i-e '52' is passed. – Asad Sarwar Dec 06 '16 at 07:54
  • FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 20 '19 at 20:56
9

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I do not understand what is the point of: `.of(Year.now().getValue(), 2, 1)` the values 2,1 can we put anything? – F.Mysir Jul 28 '22 at 19:29
  • value 2 represents the Month, value 1 represents the day. Please make sure the day is always 1 – ola357 Sep 08 '22 at 05:33
3

You did not mention what return type do you exactly need but this code should prove useful to you. sysouts and formatter are just to show you the result.

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.WEEK_OF_YEAR, 30);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(formatter.format(cal.getTime()));
cal.add(Calendar.DAY_OF_WEEK, 6);
System.out.println(formatter.format(cal.getTime()));
MarioDS
  • 12,895
  • 15
  • 65
  • 121
mezzie
  • 1,276
  • 8
  • 14
0

This answer is pretty much same as others. But, here it goes:

int year = 2018;
int week = 27;
int day = 1; //assuming week starts from sunday
Calendar calendar = Calendar.getInstance();
calendar.setWeekDate(year, week, day);
System.out.println(calendar.getTime());
Ashish Sharma
  • 617
  • 6
  • 15
0
for(int i=1; i<=7; i++) {
            if(i <= 3) {
                LocalDate desiredDate = LocalDate.now()
                        .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
                        .with(TemporalAdjusters.previousOrSame(DayOfWeek.of(i)));
                System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
            } else {
                LocalDate desiredDate = LocalDate.now()
                        .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
                        .with(TemporalAdjusters.nextOrSame(DayOfWeek.of(i)));
                System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
            }
        }

This snippet provides dates starting from monday to sunday based on the given week number output:

  • 28/06/2021
  • 29/06/2021
  • 30/06/2021
  • 01/07/2021
  • 02/07/2021
  • 03/07/2021
  • 04/07/2021

To verify check https://www.epochconverter.com/weeks/2021