点赞 + 收藏,开发直接用
计算两个时间工作日天数差。
- 方法忽略法定节假日;
- 忽略周末补充上班;
- stop当天算入计算天数;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * https://gitee.com/rodert/JavaPub */ public class CalcWorkDays { public static void main(String[] args) throws ParseException { LocalDateTime localDateTimeStart = LocalDateTime.ofInstant(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2022-01-01 01:30:10").toInstant(), ZoneId.systemDefault()); LocalDateTime localDateTimeEnd = LocalDateTime.ofInstant(new SimpleDateFormat("yyyy-MM-dd").parse("2022-12-31").toInstant(), ZoneId.systemDefault()); System.out.println(localDateTimeStart + " ~ " + localDateTimeEnd + " 包含工作日:" + getTimeDiffDay(localDateTimeStart, localDateTimeEnd)); /** * 计算两个时间工作日天数差。 * 1. 方法忽略法定节假日; * 2. 忽略周末补充上班; * 3. stop当天算入计算天数; * * @param localDateTimeStart * @param localDateTimeStop * @return * @throws ParseException */ public static int getTimeDiffDay(LocalDateTime localDateTimeStart, LocalDateTime localDateTimeStop) throws ParseException { if (localDateTimeStart.isAfter(localDateTimeStop)) { return -1; } System.out.println(localDateTimeStart); Date begin = Date.from(localDateTimeStart.atZone(ZoneId.systemDefault()).toInstant()); Date endTime = Date.from(localDateTimeStop.atZone(ZoneId.systemDefault()).toInstant()); Calendar cEnd = new GregorianCalendar(); cEnd.setTime(endTime); // 计算时算入stop当天 cEnd.add(Calendar.DATE, 1); Date end = cEnd.getTime(); Calendar c = Calendar.getInstance(); c.setTime(begin); int count = 0; while (c.getTime().before(end)) { // 非周末 if (c.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && c.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) { count++; } c.add(Calendar.DATE, 1); } return count; } }