java - 我想通过比较两天来打印31个工作日,它应该以有效格式打印日期

我要输入开始日期和结束日期。我越过第30天时,就会根据工作日从开始日期到结束日期进行迭代,这是我要打破的条件,我想打印确切的第30天。当我打印第31个日期时,它没有给出有效的格式。它给出了以下输出:

31st date isjava.util.GregorianCalendar[time=1103308200000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2004,MONTH=11,WEEK_OF_YEAR=51,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=353,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0] 31


下面是我的代码:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.openqa.selenium.WebDriver;

public class DateDifferences_Validation {
    static WebDriver driver;
    public static void main(String[] args) {
        String startdate = "06/09/2004";
        String enddate = "18/12/2004";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try
        {
          Calendar start = Calendar.getInstance();
          start.setTime(sdf.parse(startdate));
          Calendar end = Calendar.getInstance();
          end.setTime(sdf.parse(enddate));
          int workingDays = 0;
          while(!start.after(end))
          {
            int day = start.get(Calendar.DAY_OF_WEEK);
            if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY))
            workingDays++;
            start.add(Calendar.DATE, 1);
            if(workingDays>30){
                System.out.println("31st date is"+ end);
                break;
            }
          }
          System.out.println(workingDays);
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
}}

最佳答案

它不起作用,因为end对象是日历,而不是日期。您需要通过调用end.getTime()来获取Date对象,然后可以对其进行格式化:

        if(workingDays>30){
            // Raw display
            System.out.println("31st date is "+ end.getTime());

            // Formatted display
            System.out.println("31st date is "+ sdf.format( end.getTime() ));

            break;
        }


输出:

31st date is Sat Dec 18 00:00:00 CET 2004
31st date is 18/12/2004
31