Free computer code on screen

Change a String to a Date in Salesforce

Within Salesforce, Apex enables the conversion of a string into either a date or a DateTime. In this blog, we’ll demonstrate the process of converting a string into a date using Apex.

Utilizing Date.parse for String-to-Date Conversion in Salesforce

The Date class in Apex includes a method called parse, which offers one of the easiest ways to convert a String into a Date.

Some prerequisites for using the Date.valueOf method:

  • Date.parse method’s functionality depends on the locale.
  • It utilizes the local date format for parsing the string.
  • This means providing the method a date formatted according to our organization’s specifications.

Here’s a glimpse of sample Apex code demonstrating the conversion of a string into a date.

Date sampleDate = Date.parse('12/27/2023');

System.debug(sampleDate);

//The result that gets printed
2023-12-27 00:00:00

DUPLICATE CODE

What occurs when a date is provided in an incorrect format? Apex triggers a System.TypeException: Invalid date error. Let’s illustrate this with an example. We’ll input the day value where the month is typically expected.

Date sampleDate = Date.parse('27/12/2023');

System.debug(sampleDate);

//Here’s the exception that gets thrown
System.TypeException: Invalid date: 27/12/2023

DUPLICATE CODE

Date.parse tends to be effective primarily in straightforward situations.

Leveraging Date.valueOf for String-to-Date Conversion in Salesforce

The Apex Date class includes the valueOf method, which accepts a string input and converts it into a Date.

Preconditions for using the Date.valueOf method:

  • It requires utilizing the local time zone.
  • The String format should follow this structure: yyyy-MM-dd HH:mm:ss.
  • Specifying hours, minutes, or seconds is optional.

Here’s an example of code demonstrating the use of Date.valueOf to convert a String into a Date.

Date sampleDate = Date.valueOf('2023-12-23');

System.debug(sampleDate);

DUPLICATE CODE

What occurs if we input an incorrectly formatted String? Let’s input the month value where the day should be.

Date sampleDate = Date.valueOf('2023-23-12');

System.debug(sampleDate);

DUPLICATE CODE

Apex triggers a System.TypeException: Invalid date exception. Ensure the String is in the correct format to avoid this error.