Why Date. parse is not working as expected?

1.1K    Asked by Ankesh Kumar in Salesforce , Asked on Jul 19, 2021

I am struggling with an issue where Date. parse method is throwing an exception - "InValidDate". Scenario - A record with date value created in the US (Locale US(English)) and when it fetched in different locale e.g. English(Australia) then it throws an exception. Please help me to resolve the mentioned issue. Why does Date.parse give incorrect results? When to use date.parse?

Answered by Carole Thom

If you’re trying to parse any Date string into a Date with the apex on Salesforce and you don’t know the format in which the date will be given to you. To resolve this issue you have to use some combinations as seen in the below example.

This example is from this dev forum link. Hope this helps.

    // -------------------------------------------------------- // parseDate; null is invalid Date; yyyy-mm-dd and locale-specific e.g. mm/dd/yyyy or dd/mm/yyyy formats supported // -------------------------------------------------------- public static Date parseDate(String inDate) { Date dateRes = null; // 1 - Try locale specific mm/dd/yyyy or dd/mm/yyyy try { String candDate = inDate.substring(0,Math.min(10,inDate.length()));// grab date portion only m[m]/d[d]/yyyy , ignore time dateRes = Date.parse(candDate); } catch (Exception e) {} if (dateRes == null) { // 2 - Try yyyy-mm-dd try { String candDate = inDate.substring(0,10); // grab date portion only, ignore time, if any dateRes = Date.valueOf(candDate); } catch (Exception e) {} } return dateRes; } @isTest private static void testParseDate() { System.assertEquals(Date.newInstance(2020,1,1), parseDate('2020-01-01')); System.assertEquals(Date.newInstance(2020,1,1), parseDate('2020-01-01T01:09:00Z')); System.assertEquals(Date.newInstance(2020,1,1), parseDate('01/01/2020')); System.assertEquals(Date.newInstance(2020,1,1), parseDate('1/1/2020')); System.assertEquals(Date.newInstance(2020,1,1), parseDate('01/01/2020 05:08:00.000-0800')); System.assertEquals(null, parseDate(null)); System.assertEquals(null, parseDate('')); System.assertEquals(null, parseDate('ab/de/1201')); System.assertEquals(null, parseDate('13/01/2020')); System.assertEquals(null, parseDate('2020-13-01')); }

When to use date.parse?

It is not recommended to use Date. parse as until ES5, parsing of strings was entirely implementation-dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).



Your Answer

Interviews

Parent Categories