gpt4 book ai didi

java - 获取工作日 getter

转载 作者:行者123 更新时间:2023-12-01 11:16:58 24 4
gpt4 key购买 nike

我想获取两个日期之间的工作日,返回类型应该是由工作日组成的字符串数组,例如(“星期日”,“星期一”......等),您能帮我澄清这个问题吗?我对此一无所知

根据我的问题,我想获取开始日期结束日期之间的工作日,如下所示

SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy");
String startDate="01/07/2015";
String endDate="31/07/2015";
try {
Date sDate=myFormat.parse(startDate);
Date eDate=myFormat.parse(endDate);


} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

最佳答案

首先,尝试找出开始日期和结束日期之间的天数差异:

long startTime = sDate.getTime();
long endTime = eDate.getTime();
long differenceMillis = endTime - startTime;
// divide by the number of millis per day
int differenceInDays = Math.ceil((double) differenceMillis / MILLIS_PER_DAY);

然后,您可以找到您的间隔从一周中的哪一天开始:

Calendar startCal = Calendar.getInstance();
startCal.setTime(sDate);
// if you need to skip the actual start day from the interval, add a day to the calendar
int dayOfWeek = startCal.get(DAY_OF_WEEK);

获得一周的开始日期和日期之间的差异后,您可以循环并将适当的值添加到结果列表中:

List<String> days = new LinkedList<>();
for (int i = 0; i < differenceInDays; i++) {
dayOfWeek++;
if (7 < dayOfWeek) {
// if we have reached the last day of the week, we reset to the first day of the week
dayOfWeek = 1;
}

switch (dayOfWeek) {
case Calendar.SATURDAY:
days.add("Saturday");
break;
// add other cases here
}
}

这应该是您需要遵循的基本步骤。该代码只是一个示例,您可以对其进行优化和调整以使用最佳实践。

编辑:修复了 for 循环中的错误 - dayOfWeek 应在每次迭代中增加 1,而不是 i。现在应该可以正常工作了。

关于java - 获取工作日 getter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31705191/

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