Java 日期增加一天、一周、一月、三月和六月以及判断是否周末
程序员文章站
2022-04-28 18:31:16
...
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;
}
上一篇: Java 数据脱敏工具类
下一篇: 程序员成长之路——某银行项目学习笔记