function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Support Manager 2Support Manager 2 

DateTime addHours not working

Hi, I am trying to add hours in a datetime in apex. It seems that it is not working, am I missing something?
Below is the code:
@istest

class DateFormatTest {

   static testmethod void test() {
        String myDtString;
        String timestart = '2016-09-02 18:15:26';
        Datetime dt = Datetime.valueOf(timestart);
        
        myDtString = dt.format('MM/dd/yyyy hh:mm a');
        System.debug('1: '+ myDtString); //result: 1: 09/02/2016 06:15 PM
        
        dt.addHours(3);
        myDtString = dt.format('MM/dd/yyyy hh:mm a');
        System.debug('2: '+ myDtString); //result: 2: 09/02/2016 06:15 PM

   }
}

If you look at it, the results are the same after adding 3 hours.
Best Answer chosen by Support Manager 2
JLA.ovhJLA.ovh
Replace the line "dt.addHours(3);" with "dt=dt.addHours(3);"

All Answers

JLA.ovhJLA.ovh
Replace the line "dt.addHours(3);" with "dt=dt.addHours(3);"
This was selected as the best answer
UC InnovationUC Innovation
Hi.

Try doing something like this instead
 
@istest

class DateFormatTest {

   static testmethod void test() {
        String myDtString;
        String timestart = '2016-09-02 18:15:26';
        Datetime dt = Datetime.valueOf(timestart);
        
        myDtString = dt.format('MM/dd/yyyy hh:mm a');
        System.debug('1: '+ myDtString); //result: 1: 09/02/2016 06:15 PM
        
        dt = dt.addHours(3);
        myDtString = dt.format('MM/dd/yyyy hh:mm a');
        System.debug('2: '+ myDtString); //result: 2: 09/02/2016 06:15 PM

   }
}

I have come across this before and its a real pain the first time around. 

Hope this helps!

AM
Support Manager 2Support Manager 2
Thank you very much! It solve the issue.