Free computer code on screen

Transform a String into a Date in Salesforce.

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:

  1. Date.parse is influenced by the locale setting.
  2. 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

DUPLICATE CODE

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

DUPLICATE CODE

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:

  1. The local time zone should be employed.
  2. The String must follow the format: yyyy-MM-dd HH:mm:ss.
  3. 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);

DUPLICATE CODE

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.