DateTime.newInstance vs DateTime.newInstanceGMT in APEX
Working with DateTime variable is sometimes confusing. Specially when you need to generate DateTime for specific purpose in your apex code and you dont know behaviour of various DateTime functions.
Salesforce stores all DateTime fields in UTC format.Hence, You get UTC formatted values for DateTime fields, whenever you query the DateTime fields via SOQL/APEX.
However, Salesforce adjust the DateTime field values as per users time zone preference on salesforce UI. Hence, User sees the DateTime field values in their respective time zone on salesforce UI.
There are two variations for date.newInstance as below,
- DateTime.newInstance
- DateTime.newInstanceGmt
DateTime.newInstance:
- Used for constructing a DateTime from the specified date and time in the local time zone.
- It returns date in local time zone in UTC time format.
- Its signature is as follows,
Public static Datetime newInstance(Date date, Time time)
4. Below code snippet will provide date 2024–10–19 05:34:03. This is because time provided in myTime variable i.e 7:34:3 is in local time zone of logged in user i.e CET format. This local time gets converted in to UTC format.i.e 05:34:03.
Date myDate = Date.newInstance(2024, 10, 19);
Time myTime = Time.newInstance(7, 34, 3, 0);
DateTime dt = DateTime.newInstance(myDate, myTime);
system.debug('date time ' + dt);
Output=>
19:35:44:028 USER_DEBUG [5]|DEBUG|date time 2024-10-19 05:34:03
datetime.newInstanceGMT
- Used for constructing a DateTime from the specified date and time in the GMT time zone.
- Use this function, if you know exact date and time in GMT and want to generate datetime out of it.
- Its signature is as follows,
public static Datetime newInstanceGmt(Date date, Time time)
3. Below code snippet will provide date 2024–11–01 10:03:00. This is same as time provided in myTime variable i.e 10:03:00.
Date myDate = Date.newInstance(2024, 11, 1);
Time myTime = Time.newInstance(10, 03, 0, 0);
DateTime dt = DateTime.newInstanceGMT(myDate, myTime);
system.debug('date time ' + dt);
Output
10:06:05:001 USER_DEBUG [5]|DEBUG|date time 2024-11-01 10:03:00
Reference: