gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:00:06 26 4
gpt4 key购买 nike

我正在计算开始日期和结束日期。一旦超过第 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

关于java - 我想通过比较两天来打印 31 个工作日。它应该以有效格式打印日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51709686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com