简体   繁体   中英

Find start-end date of a week from week number

I build a web-application with servlet and JSPs and inside my Servlet I compute the number of the week:

 private int findWeekNumber(String myDate) 
    throws ParseException{
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        date = df.parse(myDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week = cal.get(Calendar.WEEK_OF_YEAR);
        System.out.println("week number is:" + week);

        return week;
    }

and then I save the week to my Database. Then I retrieve the week from my Database. How can I get the start - end dates of the week (Week start is Monday) from the week ? Lets say the weekNumber is 30 and I want to compute the 20/07/2015 - 26/07/2015. The same function is here

The Java 8 version

LocalDate week = LocalDate.now().with(ChronoField.ALIGNED_WEEK_OF_YEAR, yourWeekNumber);

LocalDate start = week.with(DayOfWeek.MONDAY);
LocalDate end = start.plusDays(6);
System.out.println(start +" - "+ end);

From week number:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
int year = cal.get(Calendar.YEAR);

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);


calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.DAY_OF_WEEK, 1);
   // Now get the first day of week.
Date sDate = calendar.getTime();
System.out.println(sDate);

calendar.set(Calendar.WEEK_OF_YEAR, (week));
calendar.set(Calendar.DAY_OF_WEEK, 7);
Date eDate = calendar.getTime();
System.out.println(eDate);

Another Solution

Iff - without week number

Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);

Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6); 
Date weekEnd = c.getTime();

System.out.println(weekStart);
System.out.println(weekEnd);

You can use Calendar for this,

 Calendar cal = Calendar.getInstance();
 cal.set(Calendar.WEEK_OF_YEAR, week);
 Date yourDate = cal.getTime();

 cal.setTime(yourDate);//Set specific Date of which start and end you want

 Date start,end;

 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
 start = cal.getTime();//Date of Monday of current week

 cal.add(Calendar.DATE, 6);//Add 6 days to get Sunday of next week
 cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
 end = cal.getTime();//Date of Sunday of current week
 System.out.println(start +" - "+ end);

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