Skip to main content
Nelle Hunter が「#Apex」で質問
Hi Everyone,

I have an Apex class that popluates a series of DateTime fields in order to date stamp a record as it moves through a process. They are all populated with System.Datetime.now(). The problem is some show the actual time, while others are rounded to an hour almost 12 hours previous.

DateTimes in green are correct. DateTimes in red are incorrect. They should be around 3:30 PM, not 3:00 AM.

DateTime fields not populating correctly via Apex

Code:

User-added image

Has anyone else observed this? Any idea how to resolve it?

Thanks in advance!
5 件の回答
  1. 2024年7月2日 3:18

    To get the current date and time in GMT, use System.now().

    To convert a DateTime to a specific time zone, you can use DateTime methods such as format(). 

    DateTime nowGMT = System.now();

    String nowString = nowGMT.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'', 'GMT');

    System.debug('Current GMT Time: ' + nowString);

     DateTime Rounding: If your code is performing any arithmetic operations on DateTime fields, ensure that it is not inadvertently causing rounding. For example, adding or subtracting durations might round the DateTime to the nearest hour if not handled correctly. 

    DateTime currentTime = System.now();

    DateTime roundedTime = currentTime.addHours(0); // Ensure no rounding occurs

0/9000