Home > front end >  Get start date and end date from week/month/year
Get start date and end date from week/month/year

Time:12-08

I need to extract the start date and end date from a given year, month and week and return them as LocalDate:

Example: year / month / week : 2022 / 12 / 49 -> date_begin 05/12/2022 - date_end 11/12/2022

Is there any java built in library that helps achieve this?

CodePudding user response:

JSR310 had the YearWeek, but the somewhat simpler java.time does not - hence, the simplest way is through the parser even if you don't actually need to parse it:

int weekYear = 2022;
int weekNum = 49;
LocalDate monday = LocalDate.parse(String.format("d-Wd-1", weekYear, weekNum), DateTimeFormatter.ISO_WEEK_DATE);
LocalDate sunday = monday.plusDays(6);
System.out.printf("Week %d of year %d runs from %s to %s\n", weekNum, weekYear, monday, sunday);

NB: The format is e.g. 2022-W49-1; the 1 is for 'monday'. Note that this is weekyears: That means the start date could be in the previous year (e.g. week 1 of certain years starts on december 30th in the previous year), or the end date could be in the next year. This is obvious if you think about it (weeks exist that start in one year and end in the next, and they have to be part of some year's 'week-year' system). Just thought I'd highlight it :)

CodePudding user response:

This solution also works

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;

public class Main {
    
    public static final WeekFields US_WEEK_FIELDS = WeekFields.of(DayOfWeek.SUNDAY, 4);

    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2022, 12, 29);
        LocalDate date2 = LocalDate.now();
        System.out.println(formatDate(date1));
        System.out.println(formatDate(date2));
    }
    
    public static int getWeek(LocalDate date) {
        return date.get(US_WEEK_FIELDS.weekOfWeekBasedYear());
    }
    
    public static int getMonth(LocalDate date) {
        return date.getMonthValue();
    }

    public static int getYear(LocalDate date) {
        return date.get(US_WEEK_FIELDS.weekBasedYear());
    }
    
    public static String formatDate(LocalDate date) {
        int week = getWeek(date);
        int month = getMonth(date);
        int year = getYear(date);
        return year   "/"   month   "/"   week;
    }

}

When running I get in the console

2022/12/52
2022/12/49
  • Related