In Salesforce, Apex can be utilized for converting a string into either a date or a DateTime. In this blog post, we will demonstrate the process of converting a string into a date using Apex.
Utilizing Date.parse to transform a String into a Date within Salesforce.
The Apex Date class includes a method known as “parse,” which is arguably the most straightforward approach for converting a String into a Date in Apex.
Here are some important considerations when using the Date.parse method:
- Date.parse is influenced by the locale setting.
- The local date format is employed to interpret the input string. Therefore, the method expects the date to be provided in the format used by your Salesforce organization.
Now, let’s examine some sample Apex code illustrating how to convert 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
What occurs when we supply a date in an incorrect format? Apex will raise an exception called System.TypeException: Invalid date. Let’s explore this with an example. We will insert the day value in the location 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
Date.parse typically functions effectively for straightforward scenarios only.
Applying Date.valueOf for converting a String into a Date within Salesforce.
The Apex Date class includes the “valueOf” method as well, allowing us to input a string that will be transformed into a Date.
Here are the prerequisites for utilizing the Date.valueOf method:
- The local time zone should be employed.
- The String must follow the format: yyyy-MM-dd HH:mm:ss.
- Providing the hours, minutes, or seconds is not mandatory.
Here’s a sample code snippet demonstrating the use of Date.valueOf to convert a String into a Date.
Date sampleDate = Date.valueOf('2023-12-23'); System.debug(sampleDate);
What occurs if we present a String with an incorrect format? Let’s insert the month value in the location where the day is typically expected and see the result.
Date sampleDate = Date.valueOf('2023-23-12'); System.debug(sampleDate);
Apex triggers the System.TypeException: Invalid date exception. Ensure that you provide the String in the correct format.