7

こんにちは、私はこのコードを使用して (週末を含む) 稼働日を設定しようとしていますが、2 つの日付の間で週末を除外するにはどうすればよいですか?

public long getDifferenceDays(Date d1, Date d2) {
  long diff = d2.getTime() - d1.getTime();
  long diffDays = diff / (24 * 60 * 60 * 1000);
  return diffDays;
}
4

2 に答える 2

12

これはあなたのために働くでしょう

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
于 2013-08-21T11:17:04.863 に答える
0

次のコードを使用できます。

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;
    }
 }
于 2013-08-21T10:29:49.967 に答える