1

I have date format something like this. I don't know how to format this and this value needs to used on a close date in Opportunities. Please help me to format this. I tried below but throwing errors like invalid date format.

String data = '20/12/2020  00:00:00';
System.debug('dt'+date.parse(data));
1
  • Presume you mean parse - go from a string to an Apex date object? – Keith C Jan 15 at 16:56
2

Apex doesn't have pattern-based date parsing as many other languages do. So for an unsupported format, and to be sure the code will work whatever locale the user has set, you need to write a few lines of code such as this customParse method:

@IsTest
private class CustomParseTest {

    private static Date customParse(String s) {
        String[] dt = s.split('  ');
        String[] parts = dt[0].split('/');
        return Date.newInstance(
            Integer.valueOf(parts[2]),
            Integer.valueOf(parts[1]),
            Integer.valueOf(parts[0])
        );
    }

    @IsTest
    static void test() {
        String s = '20/12/2020  00:00:00';
        Date d = customParse(s);
        System.assertEquals(Date.newInstance(2020, 12, 20), d);
    }
}
0

You have to remove the unexpected time part :

String data = '20/12/2020 00:00:00';

1.Remove the time part with substring

String stringDate = data.substring(0,10);

output : DEBUG | stringDate = 20/12/2020

2.Convert the string to date with Date.parse function

Date dt = Date.parse(stringDate);

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.