gpt4 book ai didi

java - 在 main() 中调用 int 函数来显示当前工作日

转载 作者:行者123 更新时间:2023-11-30 04:29:20 24 4
gpt4 key购买 nike

我对java很陌生,发现下面的代码可以获取不包括周六和周日的工作日数。

我需要知道如何在 main() 中调用此函数来显示当月的workDays

谢谢。

package mypkg;

import java.sql.Date;
import java.util.Calendar;

public class workrays {

public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
Calendar startCal;
Calendar endCal;
startCal = Calendar.getInstance();
startCal.setTime(startDate);
endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;

//Return 0 if start and end are the same
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
return 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.SATURDAY
&& startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis());

return workDays;
}

public static void main(String args[]) {

getWorkingDaysBetweenTwoDates(Date startDate, Date endDate);
System.out.println(workdays);
}
}

最佳答案

首先,您应该使用java.util.Date,而不是java.sql.Date。其次,您需要先创建 Date 实例,然后再将其发送到 getWorkingDaysBetweenTwoDates 函数。第三,您需要将 getWorkingDaysBetweenTwoDates 函数的结果存储在局部变量中,然后使用它。为了创建 Date,您可以使用 SimpleDateFormat 对象:

public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date startDate = sdf.parse("2013-02-20");
Date endDate = sdf.parse("2013-02-22");
int workdays = getWorkingDaysBetweenTwoDates(startDate, endDate);
System.out.println(workdays);
} catch (Exception e) {
System.out.println("There's an error somewhere. Check the stacktrace to find it");
e.printStackTrace(System.out);
}
}
<小时/>

根据您的评论,您可以创建另一个函数,通过发送 Date 来返回包含第一个日期值的 Date 实例:

public static Date getFirstDateOfMonth(Date aDate) {
Calendar c = Calendar.getInstance();
c.setTime(aDate);
c.set(Calendar.DATE, 1);
return c.getTime();
}

你可以这样调用它:

public static void main(String[] args) {
Date endDate = new Date(); //current date/time
Date startDate = getFirstDateOfMonth(endDate);
int workdays = getWorkingDaysBetweenTwoDates(startDate, endDate);
System.out.println(workdays);
}

关于java - 在 main() 中调用 int 函数来显示当前工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15035224/

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