2

I want to schedule cron expression for one day beafore the Event's StartDateTime field. So is there any method like addDays() to subtract days from DateTime Value?

3

2 Answers 2

6

As per the other answer, the various add* methods support negative values for subtractions.

However, if you want the time for your StartDateTime field to remain the same, even when subtracting the day will take you back through a Daylight Savings Transition, you need to do this in two parts; the date and the time separately:

Datetime newValue = Datetime.newInstance(
                        StartDateTime__c.date().addDays(-1),
                        StartDateTime__c.time());

Remember that Datetime values are actually stored in UTC (Salesforce calls it "GMT"). Dates and Times are not stored this way.

If you don't first split the Datetime into a Date and a Time you will discover that Datetime.addDays actually works by adding the given value multiplied by 24 to the underlying UTC value; i.e. it works in hours and ignores timezone aspects. Thus DST transitions can throw this off - to keep the same hour of day in the user timezone you may have to add or subtract 23 or 25 hours in such cases, depending on what the DST transition is.

By splitting in to the two components you remove this issue since Date.addDays literally works in days, not hours, and is outside of any time zone. Recombining the date and the time then does this in a time zone sensitive manner.

The following code, when run in UK timezone where this autumn's DST transition is on 30th October at 02:00 in the morning, demonstrates this issue:

Datetime startTime = Datetime.newInstance(2022, 10, 30, 15, 30, 0);

Datetime datetimeSubtractDay = startTime.addDays(-1);
Datetime datetimeSplitSubtractDay = Datetime.newInstance(startTime.date().addDays(-1), startTime.time());

System.debug('Originally: ' + startTime.format());
System.debug('Simple subtraction: ' + datetimeSubtractDay.format());
System.debug('Split subtraction: ' + datetimeSplitSubtractDay.format());

The output is as follows:

10:23:13.10 (11719375)|USER_DEBUG|[6]|DEBUG|Originally: 30/10/2022, 15:30
10:23:13.10 (11772158)|USER_DEBUG|[7]|DEBUG|Simple subtraction: 29/10/2022, 16:30
10:23:13.10 (11812885)|USER_DEBUG|[8]|DEBUG|Split subtraction: 29/10/2022, 15:30

NB: I use .format() here to ensure the output is formatted to the user's timezone (Europe/London in this case) since System.debug shows you UTC values for Datetime.

2

AddDays() method also supports negative values. If you want to subtract days you can use it as below.

Field.addDays(-value)

You must log in to answer this question.

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