Java 日期增加一天、一周、一月、三月和六月以及判断是否周末

无情 阅读:1226 2021-03-31 12:45:55 评论:0

1、日期增加指定日期

public String isWeekendOrHoliday(String date, Integer type) throws ParseException { 
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Date recorDate = format.parse(date); 
        // 日历对象 
		Calendar cal = Calendar.getInstance(); 
        // 日历对象设置Date 
		cal.setTime(recorDate); 
		switch (type) { 
		case 1: 
			// 日期添加:一周 
			cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+7); 
			break; 
		case 2: 
			// 日期添加:一个月 
			cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+1); 
			break; 
		case 3: 
			// 日期添加:三个月 
			cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+3); 
			break; 
		case 4: 
			// 日期添加:六个月 
			cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+6); 
			break; 
		default: 
			// 默认当天 
		} 
		if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { 
			cal.set(Calendar.DATE, cal.get(Calendar.DAY_OF_MONTH)+1); 
			recorDate = cal.getTime(); 
			date = format.format(recorDate); 
			return isWeekendOrHolidaySub(date); 
		} 
		recorDate = cal.getTime(); 
		return format.format(recorDate); 
	}

2、判断是否周末功能代码:

public String isWeekendOrHolidaySub(String date) throws ParseException { 
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Date recorDate = format.parse(date); 
		Calendar cal = Calendar.getInstance(); 
		cal.setTime(recorDate); 
		if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { 
			cal.set(Calendar.DATE, cal.get(Calendar.DAY_OF_MONTH)+1); 
			recorDate = cal.getTime(); 
			date = format.format(recorDate); 
			return isWeekendOrHolidaySub(date); 
		} 
		return date; 
	}

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号