How to Get Current Datetime in Apex Salesforce

The organization where I work as a Salesforce developer has a global Salesforce implementation with users in multiple time zones. When scheduling tasks or reminders, it’s crucial to ensure that each user creates these events at the correct local time.

When a user logs in to Salesforce, the system must display the current time and date adjusted to their local time zone. Additionally, tasks created should reflect the user’s local time, not the server time.

As a solution, I implemented an Apex class using the showCurrentTime() function to calculate the user’s local time based on their time zone. The code will get the user’s time zone, the current date, and the time and then adjust the time according to the user’s time zone.

Let’s learn how to get the current datetime in Salesforce using Apex code.

Get Current Datetime in Apex Salesforce

To get the current datetime value in Salesforce using Apex, navigate to the Salesforce developer console and follow the steps below.

  1. In this approach, we will create an Apex class. To do so, click on File > New > Apex Class.
    • Enter the Name of the new class and click OK.
Get current Datetime with Apex in Salesforce
  1. Enter the code below in the developer console to get the current datetime.
public class GetCurrentDateTime {
    public static void showCurrentTime() {
        DateTime now = DateTime.now();
        Integer hours = now.hour(), minutes = now.minute(), seconds = now.second();
        System.debug('Current DateTime: ' + now);
        System.debug('Current Time: ' + hours + ':' + minutes + ':' + seconds);
    }
}
  1. Now, I will break down the above code for better understanding.
    • In the above code, I created an Apex class named GetCurrentDateTime and used its static void method, indicating that the method belongs to the class rather than an instance and doesn’t return a value.
    • In the third row, I used the DateTime.now() function to fetch the current datetime.
    • To get the GMT time, I’ve used (‘Current DateTime: ‘ + now), and to display my system’s current time, I have used (‘Current Time: ‘ + hours + ‘:’ + minutes + ‘:’ + seconds).
    • After entering the code, press Ctrl + E to execute it.
    • In the Anonymous code execution window, enter the ‘class name.method name();’ as shown in the image below, then select the checkbox Open Log and click Execute.
How to get current date time in Salesforce apex
  1. In the console log, we can see the two time zones in the Display column.
    • System.debug shows the GMT value in the first row, and by calling hour(), minute(), and second(), I received the local time in the second row.