How to Convert String to Datetime in Salesforce Apex

In our Salesforce org, we have a custom form field where users manually enter the date and time for follow-up meetings. The input is captured as a string from a custom form field.

We need to convert this string input into a Datetime format so that we can create a follow-up event in the system in the GMT zone.

In this Salesforce tutorial, I explain possible ways to convert a string to a datetime in Salesforce Apex.

Convert a String to a Datetime using the valueOf() method in Salesforce Apex

In Salesforce Apex, we convert a string to a datetime using the valueOf() method or DateTime.valueOf(dateString.

Navigate to the Salesforce developer console and follow the steps below.

  1. In this approach, we will create an Apex class by selecting File > New > Apex Class.
    • Enter the class name and click on the OK button. Then, enter the code below in the developer console and save it.
public class StringToDatetime {
public static void convertDateTime() {
String dateString = '2024-09-24 15:30:00';
DateTime convertedDateTime = DateTime.valueOf(dateString);
System.debug('Converted DateTime: ' + convertedDateTime);
}
}
  1. If there are no errors in the above code, execute the anonymous window with “Ctrl+E.“
    • Enter the code below in the anonymous window and click the Execute button.
StringToDatetime.convertDateTime();
  1. In the execution log window, select the checkbox to debug only, and there you will see the Datetime value converted from the String.
String to datetime conversion in Salesforce apex

In this way, we can convert a string to a datetime data type in Salesforce Apex by following the above steps.

Convert String to GMT Datetime in Salesforce Apex

To convert a String to a Datetime in Salesforce Apex, navigate to the developer console and follow the steps below.

  1. Create a new class in the developer console and create a Class; select File > New > Apex Class.
    • Then, enter the name of the class and click OK. After this, enter the code below in the apex class and save it.
public class DatetimeConverter {
    public static String convertToGMT(String val) {

        DateTime date1 = (DateTime)Json.deserialize('"' + val + '"', DateTime.class);
        System.debug('Deserialized DateTime: ' + date1);
        
        String convertedDate = date1.formatGmt('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
        System.debug('Converted GMT DateTime: ' + convertedDate);
        
        return convertedDate;
    }
}

Let’s break down the above apex code.

In the above code, we have used two code blocks. The first one, DateTime date1, converts a string to a datetime, and String convertedDate sets the converted datetime according to the GMT zone.

  • In the method DateTime date1