Convert String to Date in Salesforce
In Salesforce we can use Apex to convert a string to a date or to convert a String to a DateTime, in this blog we will show you how to perform a string to date conversion using Apex.
Using Date.parse to convert a String to a Date in Salesforce
The Apex Date class has a method named parse. This is probably the simplest way to convert a String to a Date in Apex.
Requirements for using the Date.valueOf method:
- The Date.parse method is locale dependent.
- The local date format is used to parse the string. T means we need to feed the method a date in the format used by our org.
Let’s look at some sample apex code for converting a string to a date.
Date sampleDate = Date.parse('12/27/2023');
System.debug(sampleDate);
//The result that gets printed
2023-12-27 00:00:00
COPY CODE
What happens if we provide a date in the wrong format? Apex will throw the System.TypeException: Invalid date exception. Let’s see an example. We will provide the day value where the month should usually occur.
Date sampleDate = Date.parse('27/12/2023');
System.debug(sampleDate);
//Here’s the exception that gets thrown
System.TypeException: Invalid date: 27/12/2023
COPY CODE
Date.parse will usually only work for the simplest scenarios.
Using Date.valueOf to convert a String to a Date in Salesforce
The Apex Date class also has the valueOf method. We can feed the method a string and it will be converted to a Date.
Requirements for using the Date.valueOf method:
- The local time zone must be used
- The String should be formatted like so yyyy-MM-dd HH:mm:ss
- It is not necessary to provide the hours, minutes or seconds
Here’s is some sample code using Date.value of to convert a String to a Date
Date sampleDate = Date.valueOf('2023-12-23');
System.debug(sampleDate);
COPY CODE
What happens when we provide a String that is incorrectly formatted? Let’s provide the month value where the day should be
Date sampleDate = Date.valueOf('2023-23-12');
System.debug(sampleDate);
COPY CODE
Apex throws the System.TypeException: Invalid date: exception. Be sure to provide the String in the correct format.
If you are looking to convert a DateTime to a Date then check out this blog
Source: https://www.levelupsalesforce.com/convert-string-to-date