-1

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?

Thanks!

user755806
  • 5,707
  • 23
  • 92
  • 144

2 Answers2

1

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);
pws
  • 11
  • 2
0

You need to convert the string to a DateTime and then add days. You can format it back after

String stringDateTime = '2017-07-08T23:59:59Z';
DateTime dt = DateTime.valueOfGmt(stringDateTime);
DateTime tomorrow = dt.addDays(1);
DateTime nextMonth = dt.addMonths(1);
DateTime anniversary = dt.addYears(1);
String formattedDateTime = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
Matt Kaufman
  • 720
  • 4
  • 12