如何创建 Apex 代码来计算周一至周五上午 8 点至下午 6 点以及周六上午 8 点至下午 1 点的 72 小时服务后的确切日期/时间,同时考虑假期并使用初始日期作为根据?换句话说,我需要向该方法提供开始日期和服务时间,以便它可以计算最终日期。
我将提供两个例子:
我的初始日期/时间是 01/09/2023 08:00 am,我的服务时间是 8,所以我的最终日期应该是 01/09/2023 04:00 pm。
我的初始日期/时间是 01/09/2023 08:00:00,我的服务时间是 12 点,所以我的最终日期应该是 02/09/2023 10:00:00。在此示例中,由于我的日程安排是从周一至周五上午 8 点到下午 6 点,因此它会跳到第二天,因为在第一天下午 6 点之后,它不会计算到第二天(从上午 8 点开始)。
我尝试了以下代码,但它没有给我预期的结果。
public class DateTimeCalculator {
// Method to calculate the final date/time
public static Datetime calculateFinalDatetime(Datetime initialDatetime, Integer serviceHours) {
Integer dailyWorkHours = 8;
Datetime finalDatetime = initialDatetime;
List<Date> holidays = new List<Date>{Date.newInstance(2023, 9, 4)}; // List of holidays
while (serviceHours > 0) {
if (isWorkingDay(finalDatetime)) {
Integer hoursUntilEndOfDay = (finalDatetime.addHours(18).getTime() - finalDatetime.getTime()) / 3600000;
if (serviceHours <= hoursUntilEndOfDay) {
finalDatetime = finalDatetime.addHours(serviceHours);
serviceHours = 0;
} else {
finalDatetime = finalDatetime.addHours(16); // Adjust to 8 am of the next day
finalDatetime = finalDatetime.addDays(1);
serviceHours -= hoursUntilEndOfDay;
}
} else {
finalDatetime = finalDatetime.addHours(16); // Adjust to 8 am of the next day
finalDatetime = finalDatetime.addDays(1);
}
}
return finalDatetime;
}
// Method to check if a day is a working day
private static Boolean isWorkingDay(Datetime day) {
// Define working days (Monday to Friday) and Saturdays
return (day.format('E') != 'Sat' && day.format('E') != 'Sun') ||
(day.format('E') == 'Sat' && day.hour() >= 8 && day.hour() < 13);
}
}
有一个更好的方法,内置方法可以进行此计算,包括周末、节假日、夏令时...
转到设置 -> 营业时间。配置您的开放时间和几个公共假期。然后阅读有关developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/...的信息或搜索有关它的问题,例如stackoverflow.com/a/69723001/313628和stackoverflow.com/a/75553533/313628