I have a string like this :


that is supposed to be a date.

I need to convert it into a date like that :


How can I do that ? I tried a lot of things like converting it into a datetime and trying to format it like 'yyyy-MM-dd' but I always got this error when I run the code :

System.TypeException: Invalid date/time: 10/12/1990

  • 1
    Have you tried using Date.parse(), if you're in a locale that uses the MM/DD/YYYY date format? – David Reed Jun 12 '18 at 15:30

Why not do it yourself using String split?

    String myDate ='10/12/1990';
List<String> arrayDate = myDate.split('/');
String newDateFormat = arrayDate[2]+'-'+arrayDate[1]+'-'+arrayDate[0];

  • Thanks, that was finally the easier way to resolve that ! – dou Jun 13 '18 at 7:36

If you're located in an org that uses the MM/DD/YYYY date format, the Date.parse() method will do the hard work for you to convert your string into a Date instance. Then, you can use DateTime.format() to render the output format you desire. (Oddly, DateTime has more functionality than Date for this purpose).

Date myDate = Date.parse('10/12/1990');
    DateTime.newInstance(myDate, Time.newInstance(0, 0, 0, 0)).format('YYYY-MM-dd')
  • It's a per-user setting, actually. – sfdcfox Jun 12 '18 at 20:16
  • Doh. That makes this approach fragile. I wish there existed a Date.parseFormat(). – David Reed Jun 12 '18 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.