简体   繁体   中英

Given a calendar.week_of_year, How do I get the dates for the start and end of the week?

Given a week_of_year, how can I get the dates for the start and end of the week?

Example: Let's say the date is Jan/1/2017.

Calendar calendar = Calendar.getInstance();
// Let's assume that we've set calendar to Jan/1/2017.
Integer week_of_year = calendar.get(Calendar.WEEK_OF_YEAR)

week_of_year would return 1. Presumably, week 1 is anything between Jan/1/2017 to Jan/7/2017.

How can I reverse lookup week_of_year=1 and get the min/max of Jan/7/2017 to Jan/6/2017? or for any other valid week_of_year value.

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.WEEK_OF_YEAR, 1);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        System.out.println("Start Date: " + sdf.format(cal.getTime()));
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        System.out.println("End Date: " + sdf.format(cal.getTime()));

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