Convert String to Date in Salesforce Apex

In a recent Salesforce development task, I worked on a Salesforce application that required me to collect customer information through a web form. One of the fields in this form is the customer’s preferred appointment date, which is submitted as a string.

I had to convert the string to the date data type to save this date to the Salesforce date field. In this Salesforce tutorial, I will explain how to convert a string to date in Salesforce Apex.

Convert String to Date in Salesforce Apex

To learn how to convert a string to a date in Salesforce Apex, navigate to the Salesforce developer console and follow the steps below.

  1. To create an Apex class, click on the File in the nav bar and select New > Apex Class.
  1. Enter the new class’s name and click the OK button.
  1. Enter the code below in the developer console.
public class ConvertStringtoDate {
    public static Date convertStringToDate(String dateString) {
        return Date.valueOf(dateString);
    }
    
    public static void testConversion() {
        String validDateString = '2024-09-05';
        Date validDate = convertStringToDate(validDateString);
        System.debug('Valid Date: ' + validDate);
    }
}

Now, I will break down the above code for better understanding.

  • In the public class ConvertStringtoDate, I defined a static method as convertStringToDate.
  • The method’s return type is Date, a built-in Salesforce field type representing a date without time.
  • The function “valueOf(dateString)” converts the date string, which should be in the format YYYY-MM-DD, into a Date object.
  • We have used convertStringtoDate with validDateString as the argument, converting it into a Date data type and storing it as a valid date.
  1. After entering and saving the code, execute it in the anonymous window with ” Ctrl+E.”

In the anonymous window, enter the “Classname.testconversion();” then select the Open the log checkbox and click the Execute button.

How to convert string to date in Salesforce
  1. In the debug console, select the checkbox to debug only, and there you will see the date string converted to a date and displayed as a Valid date.
Salesforce apex convert string to date

This way, we can convert the date string to a date data type using the ‘valueOf(dateString);‘ function.

Handle Exceptions and Errors While Converting String to Date in Apex

There is a fair chance of getting errors while converting the string to a date in Salesforce Apex, and the reason might be an incorrect date format. For example, if the valid date format is YYYY-MM-DD, and you are trying to convert a date to DD-MM-YYYY format, yo