How to get current datetime as per the logged in user timezone in apex?

How to get current datetime as per the logged in user timezone in apex?

now()

The now() mehtod in Salesforce Apex returns the current Datetime based on a GMT calendar. So, system.now() and Datetime.now() returns Datetime based on a GMT calendar.

now().format()

The now().format() method in Salesforce Apex returns the current Datetime based on the user timezone settings selected in the user detail.

Sample code:

system.debug('System DateTime is ' + DateTime.now());
system.debug('System DateTime is ' + System.now());
system.debug('User DateTime is ' + DateTime.now().format());
system.debug('User DateTime is ' + System.now().format());

Output:

Leave a Reply