0

I have a scenarios where Date.parse method is throwing an exception - "InValidDate".

Scenario - A record with date value created in US (Locale US(English)) and when the it fetched in different locale e.g. English(Australia) then it throw an exception.

Please help me to resolve the mentioned issue.

Thanks,

1 Answer 1

2

If you’re trying to parse any Date string into a Date with apex on Salesforce and you don’t know the format in which the date will be given to you, you have to use some combination as seen in this 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'));

}
2
  • Thanks Saroj, The above code will work only if the Locale is same as the format but when the locale is different then it will not work. Consider the below example - Current Locale - English Australia Value to parse - 8/19/2015 [mm/dd/yyyy] Sep 21, 2015 at 8:05
  • +1 to Saroj for copy-pasting a code sample I wrote :-). @DildarHussain - can you use yyyy-mm-dd date formats throughout your system so you become locale-independent?
    – cropredy
    Sep 21, 2015 at 20:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .