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
Miranda L 2Miranda L 2 

I tried to check Datetime.now() or System.now() gives incorrect time

Hi there,
I wondering when I tried to check to find out my current date then it gives me 2 hours back time.

User-added image    Datetime cDT = System.now();
    system.debug('Date Time: '+cDT);
    String LongDate = cDT.format('EEEE, MMMM d, yyyy');
    system.debug('long Date: '+LongDate);
   datetime d = Datetime.now();
   system.debug('d: '+d);
why my current time is not showing. I have checked the company information which is the exact my location but still the time showing 2 hours back. Please guide me.
 
Best Answer chosen by Miranda L 2
Mirdul VarshneyMirdul Varshney
Hi @Miranda 
Salesforce stores the time in UTC. If you want to change 'GMT' then I suggest using the below code to convert.
Datetime UTC = System.now(); 
system.debug('Date Time: '+UTC); 
Organization orgDetails = [SELECT Id, TimeZoneSidKey FROM Organization WHERE Id = :UserInfo.getOrganizationId()]; 
String orgTime = UTC.format('yyyy-MM-dd HH:mm:ss', orgDetails.TimeZoneSidKey); 
system.debug('long Date: '+orgTime);

// EX- IST 
String IST = UTC.format('yyyy-MM-dd HH:mm:ss', 'IST');
 system.debug('IST : '+IST);


Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.
Thanks.

All Answers

Danish HodaDanish Hoda
Hi Miranda,
Please check the locale Timezone in your User record.
User-added image
Miranda L 2Miranda L 2
User-added image
I have debug to see again but it showing 

User-added image

If you see the Debug my time 14:11:33:003 but showing in debug 12:11:33
timezone is also correct according to timezone 
User-added image
please guide me


 
Mirdul VarshneyMirdul Varshney
Hi @Miranda 
Salesforce stores the time in UTC. If you want to change 'GMT' then I suggest using the below code to convert.
Datetime UTC = System.now(); 
system.debug('Date Time: '+UTC); 
Organization orgDetails = [SELECT Id, TimeZoneSidKey FROM Organization WHERE Id = :UserInfo.getOrganizationId()]; 
String orgTime = UTC.format('yyyy-MM-dd HH:mm:ss', orgDetails.TimeZoneSidKey); 
system.debug('long Date: '+orgTime);

// EX- IST 
String IST = UTC.format('yyyy-MM-dd HH:mm:ss', 'IST');
 system.debug('IST : '+IST);


Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.
Thanks.
This was selected as the best answer
Miranda L 2Miranda L 2
Hello @Mirdul Varshney
Thank you 
RajandraSRajandraS
Hi there,

You can also check the below code If you want to change 'GMT'.
Timezone tz = Timezone.getTimeZone('Asia/Kolkata');
DateTime dt = Datetime.now();

system.debug('Actual Time of org ' + dt.format('yyyy-MM-dd HH:mm:ss'));

system.debug('Current Local Time ' + dt.addSeconds((tz.getOffset(dt)/1000)));