parse vs valueOf for Date in Apex

If you look at the static method prototypes for Date.parse and Date.valueOf for apex, each accepts a String and each returns a new Date instance. You have to read the example in the description to know the difference — in reality each only accepts one of the two common formats: dd/MM/YYYY and YYYY-MM-dd; parse() accepts the former whereas valueOf() accepts the latter.

Consider this snippet, which passes all assertions:

Date confirmedDate = Date.newInstance(1983, 10, 11);

Date toCheck;
toCheck = Date.parse('10/11/1983');
System.assertEquals(confirmedDate, toCheck);
toCheck = Date.valueOf('1983-10-11');
System.assertEquals(confirmedDate, toCheck);

try {
  // throws System.TypeException: Invalid date: 1983-10-11
  toCheck = Date.parse('1983-10-11'); 
  System.assert(false);
}
catch (TypeException e) {
  // observed
}

try {
  // throws System.TypeException: Invalid date: 10/11/1983
  toCheck = Date.valueOf('10/11/1983'); 
  System.assert(false);
}
catch (TypeException e) {
  // observed
}

So unfortunately, if you’re truly 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 of these two, as seen in this example.

Date theDate;
try {
  // parse works in the case of 10/11/1983
  theDate = Date.parse(dateString);
}
catch(Exception e) {}
if (theDate == null) {
  try {
    // valueof works in the case of 1983-10-11
    theDate = Date.valueOf(dateString);
  }
  catch(Exception e) {}
}
if (theDate == null) {
  // couldn't parse
}

WTB: php’s strtotime in apex.

This entry was tagged , , . Bookmark the permalink.

4 Responses to parse vs valueOf for Date in Apex

  1. Calvin says:

    Thanks. Finally somebody explained the difference between the two and gave an idea about how to parse date fields.

  2. Fabio says:

    That’s it mate! Thank you sooo much!

  3. Joao Teixeira Dias says:

    I’m afraid this information is not correct. Take a look at SFDC Help about date.parse(): “Constructs a Date from a String. The format of the String depends on the local date format. The following example works in SOME LOCALES eg date mydate = date.parse(’12/27/2009′);” which means that parse is dependent of user locale. The local format date for each locale can be seen here: http://login.salesforce.com/help/doc/en/admin_supported_locales.htm

    Hope it helps

    Joao

Comments are closed.