1

I have a custom object invoice in which i have three custom fields Work_Start_Time__c, Estimate_Time_To_Complete__c, and Target_Date_Time__c. We have 9 hours working hours in a day from 9 am to 7 pm.

If a user enters today's date in Work_Start_Time__c and time is 3 pm and in Estimate_Time_To_Complete__c the user puts 8 hours, then in Target_Date_Time__c the value should be 12:00 Pm of next days not the 10:00 pm of the same day in my case its shows 10:00Pm of same days in Target_Date_Time__c custom field.

Here is my trigger

trigger DailyWorkTrackersTrigger on Invoice__c (before insert, before update) {
     for(Invoice__c workObj: Trigger.new) {
         workObj.Target_Date_Time__c = workObj.Work_Start_Time__c.addMinutes(Integer.valueOf(String.valueOf(workObj.Estimate_Time_To_Complete_Hrs__c * 1000 * 60 * 60)));
     }
 }
  • 1
    If your day goes 9 to 7 then it's 10 hours, not 9. – Adrian Larson Aug 16 '16 at 11:52
1

You have outlined a textbook use case for BusinessHours. Set your default hours up to be 9 to 7. Then, you can just use the BusinessHours.add method.

You should also look up trigger best practices and move your logic to an Apex Class. Your code could look something like:

public with sharing class InvoiceService
{
    static BusinessHours defaultHours
    {
        get
        {
            if (defaultHours == null)
            {
                defaultHours = [SELECT Id FROM BusinessHours WHERE IsDefault = true];
            }
            return defaultHours;
        }
        private set;
    }
    public static void setTargetDateTime(List<Invoice__c> invoices)
    {
        for (Invoice__c invoice : invoices) setTargetDateTime(invoice);
    }
    static void setTargetDateTime(Invoice__c invoice)
    {
        Datetime start = invoice.Work_Start_Time__c;
        Long intervalHours = invoice.Estimate_Time_To_Complete_Hrs__c;
        if (start != null && intervalHours != null)
        {
            Long intervalMs = intervalHours * 60 * 60 * 1000;
            invoice.Target_Date_Time__c = BusinessHours.add(
                defaultHours.Id, start, intervalMs
            );
        }
    }
}
  • Hi Adrian thanks for your suggestion Its perfect and workin for me – Bonny Aug 16 '16 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.