Search code examples
salesforcevisualforceapexsfdc

How to add days to date time in Salesforce Apex?


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!


Solution

  • 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\'');