In Apex, Salesforce's proprietary programming language, you can convert a string to a date using the Date and DateTime classes. Here’s how you can do it:
Converting String to Date
If your string represents a date in a standard format (like YYYY-MM-DD), you can use the Date.valueOf method:
String dateString = '2024-05-29';
Date dateValue = Date.valueOf(dateString);
System.debug('Date: ' + dateValue);
Handling Different Date Formats
If your date string is in a different format, you will need to parse it accordingly. Apex does not have built-in methods for parsing non-standard date formats directly to a Date, so you might need to manipulate the string first.
Here’s an example of converting a date string in the format DD-MM-YYYY to a Date:
String dateString = '29-05-2024';
List dateParts = dateString.split('-');
Date dateValue = Date.newInstance(
  Integer.valueOf(dateParts[2]), // Year
  Integer.valueOf(dateParts[1]), // Month
  Integer.valueOf(dateParts[0]) // Day
);
System.debug('Date: ' + dateValue);
Converting String to DateTime
For converting a string to a DateTime, use the DateTime.valueOf method. The string must be in the format yyyy-MM-dd HH:mm:ss:
String dateTimeString = '2024-05-29 14:30:00';
DateTime dateTimeValue = DateTime.valueOf(dateTimeString);
System.debug('DateTime: ' + dateTimeValue);
Handling Different DateTime Formats
For non-standard DateTime strings, you can similarly manipulate the string before conversion. For example, converting a string in the format DD-MM-YYYY HH:mm:ss:
String dateTimeString = '29-05-2024 14:30:00';
List dateTimeParts = dateTimeString.split(' ');
List dateParts = dateTimeParts[0].split('-');
List timeParts = dateTimeParts[1].split(':');
DateTime dateTimeValue = DateTime.newInstance(
  Integer.valueOf(dateParts[2]), // Year
  Integer.valueOf(dateParts[1]), // Month
  Integer.valueOf(dateParts[0]), // Day
  Integer.valueOf(timeParts[0]), // Hour
  Integer.valueOf(timeParts[1]), // Minute
  Integer.valueOf(timeParts[2]) // Second
);
System.debug('DateTime: ' + dateTimeValue);
Summary
- Use Date.valueOf for standard YYYY-MM-DD date strings.
- For non-standard date formats, split the string and use Date.newInstance.
- Use DateTime.valueOf for standard yyyy-MM-dd HH:mm:ss datetime strings.
- For non-standard datetime formats, split the string and use DateTime.newInstance.
By following these methods, you can convert strings to Date and DateTime in Apex, accommodating both standard and custom formats.