Convert Date String to Date APEX
For converting a date string to date in APEX, Date.parse() and Date.valueOf is used. But to know the difference these two methods, accept only certain date string that can be parsed.
Date.parse() - accepts date string in dd/MM/YYYY format.
Date.valueOf() - accepts date string in YYYY-MM-dd format.
Date.valueOf() - accepts date string in YYYY-MM-dd format.
In this case, if you have any specified format of date that is shown in the visualforce page, but want to perform a DML operation:
Make sure split of the date received and use the Date.newInstance and construct the date before parsing and performing DML.
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 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
}
This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
ReplyDeletebest web design company in Chennai