1

I am testing add() method from BusinessHours class and am getting an unexpected result.

As per documentation:

Adds an interval of time from a start Datetime traversing business hours only. Returns the result Datetime in the local time zone.

Here's my test:

  1. Start on Monday 2/12/24
  2. Add 4 hours
  3. Get a result of 2024-02-12 13:00:00

Below are the Business Hours in my scratch org:

enter image description here

Here's the code I am executing:

Datetime startDt = Datetime.newInstance(2024, 2, 12, 9, 0, 0);

BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];
 
System.debug('Result is ' + BusinessHours.add(bh.Id,startDt,(1*4)*60*60*1000));

Here's the debug log: DEBUG|Result is 2024-02-12 21:00:00

It's the result I am expecting but in GMT instead of local. If it was local it should have been 13:00 and not 21:00.

Next I tried addGmt() to see what that would return. As per documentation:

Adds an interval of milliseconds from a start Datetime traversing business hours only. Returns the result Datetime in GMT.

Datetime startDt = Datetime.newInstance(2024, 2, 12, 9, 0, 0);

BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];
 
system.debug('ResultGmt is ' + BusinessHours.addGmt(bh.Id,startDt,(1*4)*60*60*1000));

Debug statement: DEBUG|ResultGmt is 2024-02-12 21:00:00

I am getting the same result regardless if I use add() or addGmt(). Does anybody know why?

My user's timezone is the same as the org's timezone - (GMT-8:00).

6
  • Debug logs are always in UTC (aka GMT). You would need to explicitly format the datetime value in the user time zone to see it in debug logs in something other than UTC.
    – Phil W
    Feb 20 at 19:13
  • @PhilW Are you saying that if I store the result in a field I should see the actual local value for the add() method?
    – Arthlete
    Feb 20 at 19:19
  • I suspect so, yes. Or otherwise show the value in the UI.
    – Phil W
    Feb 20 at 19:23
  • @PhilW Almost. It depends on the method you use.
    – sfdcfox
    Feb 20 at 19:27
  • 1
    @sfdcfox I did say explicitly format. I just didn't say format! ;)
    – Phil W
    Feb 20 at 19:50

1 Answer 1

1
system.debug('ResultGmt is ' + BusinessHours.addGmt(bh.Id,startDt,(1*4)*60*60*1000));

Calls DateTime#toString, which will always display in GMT. To verify this, try:

System.debug(DateTime.now().toString());

To get the correct, local time, use DateTime#format. You'll notice this gives the right time:

System.debug(DateTime.now().format());

So:

System.debug('Result is ' + 
  BusinessHours.add(bh.Id,startDt,(1*4)*60*60*1000).format()
);
1
  • Thank you, so simple but I missed it!
    – Arthlete
    Feb 20 at 19:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .