简体   繁体   中英

Get start date and end date from week/month/year

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

Example: year / month / week: 2022 / 12 / 49 -> date_begin 05/12/2022 - date_end 11/12/2022 this mean the week 49 of the year 2022 starts from 05/12/2022 and ends on the 11/12/2022. The month is irrelevant, as @rzwitserloot said in the comments. The input is provided in ints int year = 2022 and int week = 49 .

How to achieve this?

JSR310-extra 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("%04d-W%02d-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 eg 2022-W49-1; the 1 is for 'monday'. Note that this is weekyears: That means the start date could be in the previous year (eg 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:)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM