How to get DateTime in User Time Zone using Apex in Salesforce?

How to get DateTime in User Time Zone using Apex in Salesforce?

DateTime field values are stored as Coordinated Universal Time (UTC). When a dateTime value is returned in Salesforce, it’s adjusted for the time zone specified in your org preferences. SOQL queries, however, return dateTime field values as UTC values. If you want to process these values in different time zones, your application might need to handle the conversion.

Sample Code:

Account acc = [ 
    SELECT Id, CreatedDate 
    FROM Account 
    WHERE Id = '0015A000025NLtRQAW' 
];  
System.debug(
    'Created Date is ' + 
    acc.CreatedDate
);  
System.debug(
    'Created Date is ' + 
    acc.CreatedDate.format(
        'YYYY-MM-dd hh:mm:ss'
    )
);

Output:

Leave a Reply