Ora

How to get current date time in Salesforce Apex?

Published in Apex Date Time 5 mins read

To get the current date and time in Salesforce Apex, you primarily use the DateTime.now() method for the current date and time globally, and Date.today() for the current date in the user's local time zone.

Understanding Current Date and Time in Apex

Salesforce Apex provides several built-in methods within the System.Date, System.Time, and System.DateTime classes to retrieve and manipulate date and time values. The choice of method depends on whether you need the full date and time, just the date, or need to consider time zones.

Key Methods for Current Date and Time

Here are the most common methods to retrieve the current date and time:

  • DateTime.now(): This method returns the current DateTime value in Greenwich Mean Time (GMT). It's the most straightforward way to get the precise current moment globally.
  • Date.today(): This method returns the current Date value, without time components, in the context of the running user's local time zone.
  • Date.todayGmt(): This method returns the current Date value in GMT, without time components.

Code Examples for Current Date and Time

// Get the current DateTime in GMT
DateTime currentDateTimeGmt = DateTime.now();
System.debug('Current DateTime (GMT): ' + currentDateTimeGmt);

// Get the current Date in the user's local time zone
Date currentDateUserTimeZone = Date.today();
System.debug('Current Date (User\'s Time Zone): ' + currentDateUserTimeZone);

// Get the current Date in GMT
Date currentDateGmt = Date.todayGmt();
System.debug('Current Date (GMT): ' + currentDateGmt);

// Get the current time in milliseconds since January 1, 1970, 00:00:00 GMT
Long currentTimeMillis = System.currentTimeMillis();
System.debug('Current Time in Milliseconds (GMT): ' + currentTimeMillis);

// You can create a DateTime object from milliseconds (which effectively gives current GMT DateTime)
DateTime currentDateTimeFromMillis = DateTime.newInstance(System.currentTimeMillis());
System.debug('Current DateTime from Milliseconds (GMT): ' + currentDateTimeFromMillis);

Working with Specific Date and Time Instances

Beyond retrieving the current moment, Apex also allows you to create Date, Time, and DateTime objects for specific, non-current points in time. This is useful for defining scheduled events, historical records, or future deadlines.

Creating Specific DateTime Instances

You can construct a DateTime object by specifying its components:

// Example of creating a specific DateTime object
// This is useful for representing a fixed point in time, not necessarily the 'current' time.
DateTime specificDateTime = DateTime.newInstance(2023, 5, 15, 12, 30, 0); // Year, Month, Day, Hour, Minute, Second
System.debug('A specific DateTime is: ' + specificDateTime);

// You can also create a DateTime from a Date and Time object
Date myDate = Date.newInstance(2024, 7, 20);
Time myTime = Time.newInstance(9, 0, 0, 0); // Hour, Minute, Second, Millisecond
DateTime combinedDateTime = DateTime.newInstance(myDate, myTime);
System.debug('Combined DateTime: ' + combinedDateTime);

Creating Specific Time Instances

To create a Time object representing a specific time of day:

// Example of creating a specific Time object
Time specificTime = Time.newInstance(14, 30, 0, 0); // Hour, Minute, Second, Millisecond
System.debug('A specific Time is: ' + specificTime);

Time Zone Considerations

It's crucial to understand how time zones affect date and time values in Apex:

  • GMT vs. User Time Zone: DateTime.now() and Date.todayGmt() always return values in GMT. Date.today() returns the date in the context of the user's time zone settings in Salesforce.
  • Conversions: When displaying DateTime values in the user interface, Salesforce automatically converts them to the user's local time zone based on their personal settings. However, in Apex code, you often work with GMT and can convert to a specific time zone using format(timeZone) or formatGmt(timeZone) methods if needed.

For more details on time zone handling, refer to the Salesforce Apex Developer Guide.

Summary of Date and Time Retrieval Methods

Method Description Time Zone Return Type Example
DateTime.now() Returns the current date and time. GMT DateTime DateTime.now()
Date.today() Returns the current date (no time component). User's Time Zone Date Date.today()
Date.todayGmt() Returns the current date (no time component). GMT Date Date.todayGmt()
System.currentTimeMillis() Returns the current time in milliseconds since 1/1/1970. GMT Long System.currentTimeMillis()
DateTime.newInstance(year, month, day, hour, minute, second) Creates a DateTime object for a specific point in time. GMT (internally) DateTime DateTime.newInstance(2023, 5, 15, 12, 30, 0)
Time.newInstance(hour, minute, second, millisecond) Creates a Time object for a specific time of day. N/A (time only) Time Time.newInstance(14, 30, 0, 0)

Practical Insights and Best Practices

  • Consistency: For most backend logic, it's often best to perform calculations and store DateTime values in GMT (DateTime.now()) to maintain consistency across different user time zones. Convert to the user's local time zone only when displaying or interacting with the user interface.
  • Immutability: Date, Time, and DateTime objects in Apex are immutable. Any operation that modifies a date or time (e.g., addDays(), addHours()) returns a new Date, Time, or DateTime instance rather than modifying the original.
  • Testing: When writing unit tests, avoid relying directly on DateTime.now() or Date.today() as they make tests brittle (results change daily). Instead, use Test.startTest() and Test.stopTest() in conjunction with System.setFixedHoverDateTime() or mock the date/time as needed.

By utilizing these methods effectively, you can accurately retrieve and manage current date and time information within your Salesforce Apex applications.