Convert String to Date in Salesforce Apex and Fix the Invalid Date Error

Date.valueOf() stops with this error when the text puts the month or the day first:

System.TypeException: Invalid date: 12/04/2026

To convert string to date in Apex, give Date.valueOf() the year first: Date.valueOf('2026-12-04') works. If you can’t change the incoming text, split it and build the date from its year, month and day.

The small class below does that for MM/DD/YYYY and DD-MM-YYYY, and refuses dates that don’t exist.

This Tutorial Covers: