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
Tulasiram ChippalaTulasiram Chippala 

How to convert a string to Date Time Format?

Hi 
Can we convert below string into a DateTime Format? Please help me on this.

Tue Mar 2, 2021 8pm
Suraj Tripathi 47Suraj Tripathi 47
Hi Tulasiram,

I have written an apex code that will solve your problem, please refer to the below code :
        String dateStr = 'Tue Mar 2, 2021 8pm';
        List<String> dateStrArr = dateStr.split(' ');
        DateTime dateTimeObj;
        Integer month;
        switch on dateStrArr[1] {
            when 'Jan' {    
                month = 1;
            }    
            when 'Feb' {    
                month = 2;
            }
            when 'Mar' {    
                month = 3;
            }
            when 'Apr' {    
                month = 4;
            }
            when 'May' {    
                month = 5;
            }
            when 'Jun' {          
                month = 6;
            }
            when 'Jul' {
                month = 7;
            }
            when 'Aug' {
                month = 8;
            }
            when 'Sep' {
                month = 9;
            }
            when 'Oct' {
                month = 10;
            }
            when 'Nov' {
                month = 11;
            }
            when 'Dec' {
                month = 12;
            }
        }
        if(dateStrArr[4].substring(dateStrArr[4].length()-2, dateStrArr[4].length()) == 'pm'){
            dateTimeObj = Datetime.newInstanceGmt(Integer.valueOf(dateStrArr[3]), month, Integer.valueOf(dateStrArr[2].removeEnd(',')), Integer.valueOf(dateStrArr[4].removeEnd('pm'))+12, 0, 0);
        }else if(dateStrArr[4].substring(dateStrArr[4].length()-2, dateStrArr[4].length()) == 'am'){
            dateTimeObj = Datetime.newInstanceGmt(Integer.valueOf(dateStrArr[3]), month, Integer.valueOf(dateStrArr[2].removeEnd(',')), Integer.valueOf(dateStrArr[4].removeEnd('am')), 0, 0);
        }
        System.debug('dateTimeObj:: '+dateTimeObj);

I hope you find the above solution helpful. If it does, please mark it as Best Answer to help others too.

Thanks and Regards,
Suraj Tripathi