在开发过程中,做一个工作日周期提醒。需求是根据创建时间到今天用了多少工作日,需要排除掉周末和节假日,我们来看下是怎么实现的。
1. 计算创建截止到今天的总天数
我们可以写一个工具类,来计算两个日期之间的总天数,代码如下:
public static int getBetweenDays(Date a,Date b) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
Date x=sdf.parse(sdf.format(a));
cal.setTime(x);
long time1 = cal.getTimeInMillis();
Date s=sdf.parse(sdf.format(b));
cal.setTime(s);
long time2 = cal.getTimeInMillis();
long between_days=(time1-time2)/(1000*3600*24);
int xx= Integer.parseInt(String.valueOf(between_days))+1;
return Integer.parseInt(String.valueOf(between_days))+1 ;
}
2. 计算创建截止到今天周末有几天
同样的,计算两个日期质检的周末天数也可以用一个工具类来显示:
public static int computeHolidays(Date t1,Date t2) throws ParseException{
//初始化第一个日期
Calendar cal1 = Calendar.getInstance();
//初始化第二个日期,这里的天数可以随便的设置
Calendar cal2 = Calendar.getInstance();
// 设置传入的时间格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 指定一个日期
Date date1 = dateFormat.parse(dateFormat.format(t1));
Date date2 = dateFormat.parse(dateFormat.format(t2));
// 对 calendar 设置为 date 所定的日期
cal1.setTime(date1);
cal2.setTime(date2);
int holidays = 0;
//确定一个 大日期
if(cal1.compareTo(cal2) > 0){
Calendar temp = cal1;
cal1 = cal2;
cal2 = temp;
temp = null;
}
while(cal1.compareTo(cal2)<=0){
if(cal1.get(Calendar.DAY_OF_WEEK)==1||cal1.get(Calendar.DAY_OF_WEEK)==7){
holidays++;
System.out.println("周末:"+new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
}
cal1.add(Calendar.DAY_OF_YEAR,1);
}
return holidays;
}
3. 计算创建截止到今天节假日,调休日有几天
关于节假日和调休日,我们是做了一个表格导入到数据库,通过查询数据库来获得的。
节假日天数计算:
@SuppressWarnings("unchecked")
public int findJrrqs(Date d1,Date d2){
String sql = "select a.jrrq from Jiejiari a where a.jrlx='节假日' and a.jrrq>='"+d1+"' and a.jrrq<='"+d2+"'";
return getSessionFactory().getCurrentSession().createQuery(sql).list().size();
}
调休日天数计算:
/**
* 调休天数
* @param d1
* @param d2
* @return
*/
@SuppressWarnings("unchecked")
public int findTx(Date d1,Date d2){
String sql = "select a.jrrq from Jiejiari a where a.jrlx='调休' and a.jrrq>='"+d1+"' and a.jrrq<='"+d2+"'";
return getSessionFactory().getCurrentSession().createQuery(sql).list().size();
}
接下来是通过计算来算出两个日期之间的工作日天数:总天数-周末-节假日+调休日,即:
版权声明:本文为qq_39257746原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。