嗨,我尝试使用此代码来安排工作天数(包括周末),那么我如何排除两个日期之间的周末?
public long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
return diffDays;
}
这对你有用
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("10/08/2013");
Date date2 = df.parse("21/08/2013");
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int numberOfDays = 0;
while (cal1.before(cal2)) {
if ((Calendar.SATURDAY != cal1.get(Calendar.DAY_OF_WEEK))
&&(Calendar.SUNDAY != cal1.get(Calendar.DAY_OF_WEEK))) {
numberOfDays++;
}
cal1.add(Calendar.DATE,1);
}
System.out.println(numberOfDays);
现场演示
输出
7
您可以使用以下代码:
public class DateUtils{
private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MMM-dd");
public static void main(String[] args){
try
{
Date beg = ((args.length > 0) ? DEFAULT_DATE_FORMAT.parse(args[0]) : new Date());
Date end = ((args.length > 1) ? DEFAULT_DATE_FORMAT.parse(args[1]) : new Date());
System.out.println("beg: " + DEFAULT_DATE_FORMAT.format(beg));
System.out.println("end: " + DEFAULT_DATE_FORMAT.format(end));
System.out.println("# days between: " + interval(beg, end, new IncludeAllDateRule(), Calendar.DATE));
System.out.println("# weekdays between: " + interval(beg, end, new ExcludeWeekendDateRule(), Calendar.DATE));
System.out.println("# hours between: " + interval(beg, end, new IncludeAllDateRule(), Calendar.HOUR));
System.out.println("# minutes between: " + interval(beg, end, new IncludeAllDateRule(), Calendar.MINUTE) );
}
catch (ParseException e)
{
e.printStackTrace();
}
}
public static int interval(Date beg, Date end, DateRule dateRule, int intervalType)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(beg);
int count = 0;
Date now = calendar.getTime();
while (now.before(end))
{
calendar.add(intervalType, 1);
now = calendar.getTime();
if (dateRule.include(now))
{
++count;
}
}
return count;
}
}
interface DateRule{
boolean include(Date d);
}
class ExcludeWeekendDateRule implements DateRule
{
public boolean include(Date d)
{
boolean include = true;
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if ((dayOfWeek == Calendar.SATURDAY) || (dayOfWeek == Calendar.SUNDAY))
include = false;
return include;
}
}
class IncludeAllDateRule implements DateRule
{
public boolean include(Date d)
{
return true;
}
}