In this post we will learn How To Convert Date String to Date APEX.
Manytimes We got stucked in date format like when we are inserting a record whose data is coming from response of any rest resources.
So here sometimes it through an error that date fields is invalid this is because the format of date string doesnot match with the Salesforce date fields so to overcome this problem . one need to convert date into valid apex format
To Convert a date string to Apex date we have two methods
Difference between both method is :
Date.valueOf() – accepts date string in YYYY-MM-dd format.
Datetime dt2 = Datetime.newInstance(d2.year(), d2.month(),d2.day());
And in case if you don’t know the format of the date string, use the below snippet to parse the date
Date theDate; try { // parse works in the case of 20/01/1994 theDate = Date.parse(dateString); } catch(Exception e) {} if (theDate == null) { try { // valueof works in the case of 20-01-1994 theDate = Date.valueOf(dateString); } catch(Exception e) {} } if (theDate == null) { // couldn't parse }
Hope This will help you to short out your problem..
Hits: 10273