从周数中查找一周的开始日期

时间:2015-07-24 09:22:36

标签: java date java-8

我用servlet和JSP构建了一个web应用程序,在我的Servlet中我计算了一周的数量:

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

然后我将week保存到我的数据库。然后我从我的数据库中检索week。如何从week获取一周的开始 - 结束日期(周开始是星期一)?让我们说weekNumber是30,我想计算20/07/2015 - 2015年7月26日。同样的功能是here

3 个答案:

答案 0 :(得分:7)

Java 8版

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

答案 1 :(得分:1)

从周数:

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

另一种解决方案

Iff - 没有周数

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

答案 2 :(得分:1)

您可以使用Calendar

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