How to add days to date time in Salesforce Apex

0 votes

Hi I am using Salesforce Apex, I have a date as String as below. I need to add days to it using Apex.

String dateTime = '2017-07-08T23:59:59Z';

If I add one day to it then it should be 2017-07-09T23:59:59Z as string. How will I do this?

Mar 14, 2022 in SalesForce by surbhi
• 3,820 points
8,961 views

1 answer to this question.

0 votes

Beware the DST issue! The "addDays" function is not DST-aware, so if you step over a DST transition during the addition of days (in a time zone that has DST) then the time will be messed up.

To resolve this one split the date/time into separate date and time parts first, add the days to the date part then re-combine at the end, like:

DateTime dt = ...;
Integer days = ...;
Date d = dt.date().addDays(days);
Time t = dt.time();
dt = DateTime.newInstance(d, t);

If you are working in the UK (London) time zone the following anonymous Apex illustrates the issue nicely:

DateTime dt = DateTime.newInstance(2017, 10, 28, 23, 59, 59);
System.debug('Adding days directly: ' + dt.addDays(2));
Date d = dt.date().addDays(2);
Time t = dt.time();
dt = DateTime.newInstance(d, t);
System.debug('Adding days in parts: ' + dt);

Hope this helps!

Get your Salesforce Certification today to become a certified admin & app builder.

Thanks!

answered Mar 15, 2022 by CoolCoder
• 4,420 points

edited Jun 19, 2023 by Khan Sarfaraz

Related Questions In SalesForce

0 votes
1 answer

Json response to be deserialized in Apex salesforce lightning

Because some fields in Apex Salesforce are ...READ MORE

answered Mar 2, 2022 in SalesForce by surbhi
• 3,820 points
4,287 views</