salesforce

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.parse() – accepts date string in dd/MM/YYYY format.
Date.valueOf() – accepts date string in YYYY-MM-dd format.
In this case, if you have any specified format of date
Make sure split of the date received and use the Date.newInstance and construct the date before parsing and performing DML.
String dateFormatString = ‘yyyy-MM-dd’;
Date d2 = Date.today();
Datetime dt2 = Datetime.newInstance(d2.year(), d2.month(),d2.day());
String newDate = dt.format(dateFormatString);

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

Share Post

By Himanshu Rana

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

Leave a Reply

Your email address will not be published. Required fields are marked *