While working as a Salesforce developer, I got a requirement from the sales team for our organization regarding the data type conversion of an object field. The sales team wants to track opportunities that are closing soon. The Opportunity Close Date is stored as a DateTime field, but the team only wants the date (without time) to send out reminders for daily tracking purposes.
To solve this, I used Apex programming to convert the date value to a Datetime in Salesforce. In this Salesforce tutorial, I will explain the various possible methods to convert Date value to Datetime in Salesforce Apex.
Convert Date to DateTime Format in Salesforce Apex
In the steps below, we will explore the various methods for converting a Date to a DateTime Format in Salesforce Apex.
Convert Date to DateTime Format using newInstance() method in Salesforce Apex
To convert Dates to DateTime format in Salesforce Apex, navigate to the Salesforce developer console and execute the code below in the Apex anonymous window.
Using the Datetime.newInstance method, create a Datetime from a Date object by setting the time to 00:00:00.
Date newDate = Date.today();
Datetime newDateTime = Datetime.newInstance(newDate, Time.newInstance(0, 0, 0, 0));
System.debug('Datetime: ' + newDateTime);
After executing the apex anonymous code, we can see that the date value is converted to DateTime format in the debug of the execution log window.

This way, we can convert the date values to a datetime format in Salesforce Apex using the newInstance() method.
Convert Date to DateTime Format using vaueOf() method in Salesforce Apex
This method of Date to DateTime conversion is useful when you have Date and time information as a string. The Datetime.valueOf method converts it directly into a Datetime.
Now, execute the code below in the Salesforce Apex anonymous window to convert the date value to DateTime format.
String dateString = '2024-10-15 12:30:45';
Datetime newDateTime = Datetime.valueOf(dateString);
System.debug('Date to Datetime formatted value : ' + newDateTime);
After the code execution, you will see the debug of the execution log window, where the date value is converted to the datetime value in Salesforce Apex.
