How to Calculate the Day of the Week from a Date and Actual Time Spent Between Two Date-Times in Apex
For example, if we need to track the exact amount of time a user spent on a Lead, Case, or Task, simply subtracting two date-time values won't suffice if we need to exclude non-working hours.
In this post, we will cover:
- How to determine the day of the week from a given date in Apex.
- How to calculate actual time spent between two date-times, while considering business hours (Monday to Friday: 8 AM - 8 PM, Saturday & Sunday: 8 AM - 4:30 PM).
1. How to Determine the Day of the Week from a Date in Apex
Salesforce does not provide a direct method to get the day name (Monday, Tuesday, etc.) from a Date
field. However, we can achieve this using toStartOfWeek()
and daysBetween()
methods.
How It Works
toStartOfWeek()
returns the Sunday of that week.daysBetween()
calculates how many days exist between the input date and that Sunday.- The day difference helps us map the date to its respective weekday.
Example Output
System.debug(getDayOfWeek(Date.newInstance(2025, 3, 19))); // Output: "Wednesday"
2. How to Calculate Actual Time Spent Between Two Date-Times Excluding Off-Hours
If we need to calculate the actual time spent within business hours, we must:
- Loop through each date in the range.
- Identify if the day is a weekday (Monday-Friday, 8 AM - 8 PM) or weekend (Saturday-Sunday, 8 AM - 4:30 PM).
- Consider only the hours that fall within the defined working schedule.
How It Works
- Loops through each date between
startDateTime
andendDateTime
. - Determines whether the day is a weekday or weekend using
daysBetween()
. - Sets business start and end times accordingly:
- Weekdays (Mon-Fri): 8 AM - 8 PM
- Weekends (Sat-Sun): 8 AM - 4:30 PM
- If
startDateTime
is before business hours, it adjusts to 8 AM. - If
endDateTime
is after business hours, it adjusts to closing time. - Calculates the time difference for each day within business hours.
Example Usage & Output
Expected Output:
If March 18 and 19 are weekdays:
- 10:00 AM - 8:00 PM (Day 1) → 10 hours
- 8:00 AM - 3:30 PM (Day 2) → 7.5 hours
- Total Business Hours: 17.5 hours
Conclusion
By leveraging Apex logic, we can:
✅ Determine the day of the week from a date
✅ Calculate actual time spent between two date-times while excluding non-working hours
✅ Handle weekday/weekend variations dynamically
This approach is useful in Lead tracking, Case management, Worklogs, and SLAs where accurate time calculation within business hours is required.
Would you like to extend this further with public holidays exclusion? Let me know in the comments!
Comments