java获取指定日期所在周的第一天和最后一天

第一种方式:

Date InputDate = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(20140101));
		 Calendar cDate = Calendar.getInstance();
		 cDate.setFirstDayOfWeek(Calendar.MONDAY);
		 cDate.setTime(InputDate);
		
		 Calendar firstDate = Calendar.getInstance();
		 
		 firstDate.setFirstDayOfWeek(Calendar.MONDAY);
		 firstDate.setTime(InputDate);
		 
		 
		 Calendar lastDate = Calendar.getInstance();
		 lastDate.setFirstDayOfWeek(Calendar.MONDAY);
		 lastDate.setTime(InputDate);
		 
		 if(cDate.get(Calendar.WEEK_OF_YEAR)==1&&cDate.get(Calendar.MONTH)==11){
			 firstDate.set(Calendar.YEAR, cDate.get(Calendar.YEAR)+1);
			 lastDate.set(Calendar.YEAR, cDate.get(Calendar.YEAR)+1);
		 }
		 
		 int typeNum  = cDate.get(Calendar.WEEK_OF_YEAR);
		 System.out.println(typeNum);
		 
		 firstDate.set(Calendar.WEEK_OF_YEAR, typeNum);
		 firstDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		 //所在周开始日期
		 System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(firstDate.getTime()));
		 
		 lastDate.set(Calendar.WEEK_OF_YEAR, typeNum);
		 lastDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		 //所在周结束日期
		 System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(lastDate.getTime()));

第二种方式

Calendar cal = Calendar.getInstance();

		cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2014-01-01"));

		int d = 0;
		if(cal.get(Calendar.DAY_OF_WEEK)==1){
			d = -6;
		}else{
			d = 2-cal.get(Calendar.DAY_OF_WEEK);
		}
		cal.add(Calendar.DAY_OF_WEEK, d);
		//所在周开始日期
		System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
		cal.add(Calendar.DAY_OF_WEEK, 6);
		//所在周结束日期
		System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));

最近看java8里面的新的日期处理,用java8的api取一周的开始和结束

 

LocalDate inputDate = LocalDate.parse(date);
// 计算周开始时间 = 当前日期 - (当前日期是周几 - 周一)的日期差
TemporalAdjuster FIRST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue()-DayOfWeek.MONDAY.getValue()));
System.out.println(inputDate.with(FIRST_OF_WEEK));

// 计算周开始时间 = 当前日期 + (周日 - 当前日期是周几)的日期差
TemporalAdjuster LAST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
System.out.println(inputDate.with(LAST_OF_WEEK));



java8中比较简单的方法

LocalDate inputDate = LocalDate.parse(date);
// 所在周开始时间
LocalDate beginDayOfWeek = inputDate.with(DayOfWeek.MONDAY);
// 所在周结束时间
LocalDate endDayOfWeek = inputDate.with(DayOfWeek.SUNDAY);

 

你可能感兴趣的:(java)