Mellon
Mellon

Reputation: 38842

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

Upvotes: 26

Views: 47551

Answers (7)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79005

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.

Upvotes: 11

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

Upvotes: 0

Ashish Sharma
Ashish Sharma

Reputation: 627

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());

Upvotes: 0

Mateusz Szulc
Mateusz Szulc

Reputation: 1784

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));

Upvotes: 39

mezzie
mezzie

Reputation: 1296

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()));

Upvotes: 3

bungrudi
bungrudi

Reputation: 1417

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()));    

Upvotes: 47

Alois Cochard
Alois Cochard

Reputation: 9862

You can use the joda time library

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

Upvotes: 12

Related Questions