Skip to main content

How to Calculate the Day of the Week from a Date and Actual Time Spent Between Two Date-Times in Apex

When working with Salesforce, there are instances where we need to compute the day of the week from a given date or determine the actual time spent between two date-time values, considering only business hours.

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.

public static String getDayOfWeek(Date inputDate) {
    // Get the start of the week (Sunday) for the given date
    Date startOfWeek = inputDate.toStartOfWeek();
   
    // Calculate the difference in days between the input date and the start of the week
    Integer dayDifference = inputDate.daysBetween(startOfWeek);
   
    // Determine the day of the week based on the difference
    String dayOfWeek;
    switch on dayDifference {
        when 0 { dayOfWeek = 'Sunday'; }
        when 1 { dayOfWeek = 'Monday'; }
        when 2 { dayOfWeek = 'Tuesday'; }
        when 3 { dayOfWeek = 'Wednesday'; }
        when 4 { dayOfWeek = 'Thursday'; }
        when 5 { dayOfWeek = 'Friday'; }
        when 6 { dayOfWeek = 'Saturday'; }
        when else { dayOfWeek = 'Invalid'; }
    }
   
    return dayOfWeek;
}

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"

System.debug(getDayOfWeek(Date.newInstance(2025, 3, 23))); // Output: "Sunday"

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:

  1. Loop through each date in the range.
  2. Identify if the day is a weekday (Monday-Friday, 8 AM - 8 PM) or weekend (Saturday-Sunday, 8 AM - 4:30 PM).
  3. Consider only the hours that fall within the defined working schedule.
public static Decimal calculateBusinessHours(Datetime startDateTime, Datetime endDateTime) {
    if (startDateTime == null || endDateTime == null) {
        return 0;
    }      
   
    Date startDate = startDateTime.date();
    Date endDate = endDateTime.date();    
    Decimal totalHours = 0;
   
    // Loop through each date from start to end
    for (Date currentDate = startDate; currentDate <= endDate; currentDate = currentDate.addDays(1)) {
        // Determine the day of the week (0 = Sunday, 6 = Saturday)
        Date startOfWeek = currentDate.toStartOfWeek();
        Integer dayDifference = currentDate.daysBetween(startOfWeek);
       
        // Define business hours start time (8 AM)
        Datetime businessStart = Datetime.newInstance(currentDate, Time.newInstance(8, 0, 0, 0));
        Datetime businessEnd;
       
        // Set business end time based on weekday/weekend
        if (dayDifference == 6 || dayDifference == 0) { // Weekend (Saturday = 6, Sunday = 0)
            businessEnd = Datetime.newInstance(currentDate, Time.newInstance(16, 30, 0, 0)); // 4:30 PM
        } else {
            businessEnd = Datetime.newInstance(currentDate, Time.newInstance(20, 0, 0, 0)); // 8:00 PM
        }
       
        // Determine effective start and end time for this date
        Datetime effectiveStart = (startDateTime > businessStart) ? startDateTime : businessStart;
        Datetime effectiveEnd = (endDateTime < businessEnd) ? endDateTime : businessEnd;
       
        // If within business hours, calculate time difference
        if (effectiveStart < effectiveEnd) {
            totalHours += (effectiveEnd.getTime() - effectiveStart.getTime()) / (1000 * 60 * 60); // Convert ms to hours
        }
    }
   
    return totalHours;
}

How It Works

  1. Loops through each date between startDateTime and endDateTime.
  2. Determines whether the day is a weekday or weekend using daysBetween().
  3. Sets business start and end times accordingly:
    • Weekdays (Mon-Fri): 8 AM - 8 PM
    • Weekends (Sat-Sun): 8 AM - 4:30 PM
  4. If startDateTime is before business hours, it adjusts to 8 AM.
  5. If endDateTime is after business hours, it adjusts to closing time.
  6. Calculates the time difference for each day within business hours.

Example Usage & Output

Datetime startDT = Datetime.newInstance(2025, 3, 18, 10, 0, 0); // March 18, 2025 - 10:00 AM
Datetime endDT = Datetime.newInstance(2025, 3, 19, 15, 30, 0); // March 19, 2025 - 3:30 PM
System.debug(calculateBusinessHours(startDT, endDT));

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

Popular posts from this blog

Style in LWC

 Following are the ways we can apply in CSS in LWC. 1. Inline CCS Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div < template >     < lightning-card title = "Inline CSS" >         < div >             < div style = "color:green;font-size:10px;" > This is inline Style div </ div >         </ div >     </ lightning-card > </ template >  2. External CSS style can be applied to an elements such as h1, p,div span etc. It can applied to class using "." notation. for example .user{} It can also be applied to pseudo class.  for example .user:hover{} Id locator is not being used in LWC to apply style To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is ...

Lifecycle hooks in LWC

There are 3 phase of LWC component  1. Mounting  A. constructor, B. connnectedCallback C. render D. renderedCallback 2. UnMounting  A. disconnectedcallback 3. Error  A.errorcallback Note - render is not lifecycle hook, it is protected method of Lightning element class. Mounting Phase LWC Creation and Render Life cycle Constructor Method ·        This method called when component is instantiated and It flows from parent to child component. ·        Need to call Super() inside constructor method ·        Can’t access any component properties or child component because it’s not ready yet. ·        Host element can be accessed through “this. template” inside constructor method. ·        Don’t add any attributes to host inside constructor C   constructor (){          super (); //...

How to Create/Delete file attachments(Content Document) through Apex ?

 There are 3 standard salesforce objects to store file attachments. Content Document, ContentDocumentVersion, ContentDocumentLink.  Here is the article to talk about these objects and relationship.  https://www.forcetalks.com/blog/contentdocument-and-contentversion-in-salesforce-an-overview/ ContentDocumentVersion ContentDocumentLink This post is all about how to create/delete content document though Apex. Here is code snippet // Insert Content Version record ContentVersion contentVersionRec = new ContentVersion(Title='filename',PathOnClient ='FileName.pdf',VersionData = bodyBlob,origin = 'H'); INSERT contentVersionRec; // this will insert one record in ContentDocument and ContentVersion , ContentDocument  is parent and  ContentVersion is child record // get contentdocument id contentVersionRec = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionRec .Id LIMIT 1]; // Create Content Document Link record- This will attach ...