function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PandeiswariPandeiswari 

Convert string date to Date in Apex

Hi,

I have String date as "Jul 27, 2018". How to convert to Date in Apex
Jean Grey 10Jean Grey 10
You might have to use an if to get the month, but for everything else you can use the substring and date methods.
public static Date ParsedDate (String myDate) {
    String myDate = 'Jul 27, 2018';
    Integer myMonth = 1;
    ​
    String myMonthString = myDate.substring(0,2);
    if(myMonthString=='Jul'){
        myMonth = 7;
    }
    if(myMonthString=='Aug'){
        myMonth = 8;
    }
    //more logic here to go through all the months

    String myDay = myDate.substring(4,5);
    String myYear = myDate.substring(8,11);
    Date myDateFormatted = Date.newInstance(integer.valueOf(myYear),myMonth,integer.valueOf(myDay));

    return myDateFormatted;

    }

 
Akshay_DhimanAkshay_Dhiman
Hi Pandeiswari,

Try this code snippet:
 
String todate = '12/27/2013';
    Date dt = Date.parse(todate);

if you found this answer helpful then please mark it as best answer so it can help others.
 
Thanks
Akshay
Akshay_DhimanAkshay_Dhiman
Hi Pandeiswari,

You can also try this:
 
public class ConvertStringToDate {

public  static void  convert() {

String myDate = 'Jul 27, 2018';

String target = 'Jul';
String replacement = '7,';
String s2 = myDate.replace(target, replacement);
system.debug('s2 ==>'+s2);

String month = s2.substring(0,1);
system.debug('month ==>'+month);

String day = s2.substring(3,5);
system.debug('day ==>'+day);

String year = s2.substring(7,11);
system.debug('year ==>'+year);

string stringDate = year + '-' + month
+ '-' + day;

Date myDate2 = date.valueOf(stringDate);
system.debug('myDate2 ==>'+myDate2);



}
}

Thanks
Akshay