我想获取特定月份的工作天数
在我的情况下,周末是星期五和星期六
我使用此代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class TestWeekDay {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String dateInString = "01-07-2016";
Date startDate = sdf.parse(dateInString);
String dateInString2 = "31-07-2016";
Date endDate = sdf.parse(dateInString2);
calculateDuration(startDate,endDate);
}
public static int calculateDuration(Date startDate, Date endDate)
{
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
if (startCal.getTimeInMillis() > endCal.getTimeInMillis())
{
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do
{
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY)
{
workDays++;
}
}
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
return workDays;
}
}
例如,当我测试7月时,我有22,正确的答案应该是21
最佳答案
我认为您的问题可能是由边界条件引起的,该边界条件导致评估前每个月增加一天的时间。在增加实际日期之前,请先尝试执行星期几检查。
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis()) {
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY &&
startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
workDays++;
}
startCal.add(Calendar.DAY_OF_MONTH, 1);
}