在Java中使用Calendar类来计算工作日(即排除周末)可以通过以下方法实现:
以下是一个简单的示例代码来计算指定日期范围内的工作日数量:
import java.util.Calendar;
public class WorkdayCalculator {
public static void main(String[] args) {
Calendar start = Calendar.getInstance();
start.set(2022, Calendar.JANUARY, 1);
Calendar end = Calendar.getInstance();
end.set(2022, Calendar.DECEMBER, 31);
int workdays = calculateWorkdays(start, end);
System.out.println("Number of workdays: " + workdays);
}
public static int calculateWorkdays(Calendar start, Calendar end) {
int workdays = 0;
Calendar current = (Calendar) start.clone();
while (current.before(end) || current.equals(end)) {
if (current.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && current.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
workdays++;
}
current.add(Calendar.DAY_OF_MONTH, 1);
}
return workdays;
}
}
性能优化技巧:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。