获取一段时间内,指定星期几的具体日期

 思路参考自文章:http://www.oschina.net/code/snippet_8676_2035

特别注意:Calender初始化时会根据当前时间初始化,所以就算设置了年月日,其时分秒部分仍然有值。对于比较同一天的情况下,.after()与.before()函数会将两个日期转换成整数比较,就算年月日相同,时分秒部分仍然后影响比较结果。因此推荐new Calender后执行一次.clear(),将对象清理一次,然后set年月日。

/**
	 * 
	 * @param beginDate "yyyyMMdd"
	 * @param endDate "yyyyMMdd"
	 * @param schedule 对应星期几,可包含:1234567
	 * @return "yyyyMMdd yyyyMMdd yyyyMMdd ..."
	 */
	public static String parseDateBetweenTwoDates(String beginDate, String endDate, String schedule){
		String retVal="";
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		
		List<Integer> scheduleList = getDayOfWeek(schedule);
		int year=0;
		int month=0;
		int day=0;
	
		Calendar calendar_begin = new GregorianCalendar();
		year = Integer.valueOf(beginDate.substring(0, 4));
		month = Integer.valueOf(beginDate.substring(4, 6))-1;
		day = Integer.valueOf(beginDate.substring(6));		
		calendar_begin.set(year, month, day);
		
		Calendar calendar_end = new GregorianCalendar();
		year = Integer.valueOf(endDate.substring(0, 4));
		month = Integer.valueOf(endDate.substring(4, 6))-1;
		day = Integer.valueOf(endDate.substring(6));
		calendar_end.set(year, month, day);
		calendar_end.add(Calendar.DAY_OF_YEAR,1);
		
		while(calendar_begin.before(calendar_end)){
			if( scheduleList.contains(calendar_begin.get(Calendar.DAY_OF_WEEK)) ) {
				retVal += dateFormat.format(new Date(calendar_begin.getTime().getTime())) + " ";
			}
			calendar_begin.add(Calendar.DAY_OF_YEAR,1);
		}
		
		return retVal.trim();
	}
	
	/**
	 * 
	 * @param schedule:1234567
	 * @return {0,1,2,3,4,5,6}
	 */
	private static List<Integer> getDayOfWeek(String schedule){
		List<Integer> retList = new ArrayList<Integer>();	
		if(schedule.contains("7")) retList.add(1);
		if(schedule.contains("1")) retList.add(2);
		if(schedule.contains("2")) retList.add(3);
		if(schedule.contains("3")) retList.add(4);
		if(schedule.contains("4")) retList.add(5);
		if(schedule.contains("5")) retList.add(6);
		if(schedule.contains("6")) retList.add(7);
		return retList;
	}

 

转载于:https://my.oschina.net/u/3202695/blog/819238

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值