Convert String into formated date

dou 06/12/2018 at 15:28. 2 answers, 85 views
apex date datetime

I have a string like this :

10/12/1990

that is supposed to be a date.

I need to convert it into a date like that :

1990-12-10

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

2 Answers


Pranay Jaiswal 06/12/2018 at 16:05.

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];

System.debug(newDateFormat);

David Reed 06/12/2018 at 16:14.

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');
System.debug(
    DateTime.newInstance(myDate, Time.newInstance(0, 0, 0, 0)).format('YYYY-MM-dd')
);

Related questions

Hot questions

Language

Popular Tags