[SalesForce] trigger using business hours to add hours for next business day

I have setup the default business hours specifying work days M-F 8 to 5pm EST and no hours on the Saturday and Sunday.

When I run the trigger, the new date time is created and it does skip the weekend, but the hours are off? It seems it is off by two hours early? For example, if I fire the trigger on Friday evening, I'd expect the next start time that I'm adding hours would be on Monday at 8am? But, I'm getting 6am instead.

Here is my code:

global class ArtRequestSetDueDate implements ITriggers.HandlerInterface {

Art_Request__c[] newCollection = trigger.new;
Map<Id, Art_Request__c> oldCollection = (Map<Id, Art_Request__c>)trigger.oldMap;
Boolean cacheLoaded = false;

global void handle() {
    setArtRequestDueDate();
}

private BusinessHours getDefaultBusinessHours() {
    BusinessHours bh = new BusinessHours();
    if(cacheLoaded) return bh;
    bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];
    cacheLoaded = true;
    return bh;
}

private void setArtRequestDueDate() {
    BusinessHours bh = getDefaultBusinessHours();
    for(Art_Request__c ar: newCollection) {
        if(ar.Date_Time_Assigned__c != null && oldCollection.get(ar.Id).Date_Time_Assigned__c == null) {
            Integer hours = 0;
            if(ar.Priority__c.toLowercase() == 'standard') hours = 8;
            if(ar.Priority__c.toLowercase() == 'rush') hours = 2;
            ar.Date_Time_Due__c = BusinessHours.add(bh.Id, ar.Date_Time_Assigned__c, hours);
        }
    }       
}
}

Thanks for any help.

Best Answer

This doesn't explain your two hour problem, but the last argument to BusinessHours.add is a millisecond value so you need to multiply your hours value by 1000 * 60 * 60.

A two hour difference sounds like a timezone problem, but I haven't seen any explicit timezone adjustments in sample code. I do note that there is a BusinessHours.addGMT in addition to the BusinessHours.add but I am not clear on which to use when...

Related Topic