0

How can we convert "Dec 5, 2018 3:14 PM" (with three letter month) to datetime format. Tried both Parse and ValueOf and they did not work.

DateTime.Parse('Dec 5, 2018 3:14 PM');
DateTime.ValueOf('Dec 5, 2018 3:14 PM');

We have this date in a json file that we need to process.

Even this did not work

system.debug(Json.deserialize('Dec 5, 2018 3:14 PM', DateTime.Class));
2
  • 1
    You have to manually parse string and manually create an instance of DateTime using Datetime newInstance(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer second) Mar 7, 2019 at 19:24
  • @glls This is of different format and those solutions will not work for this case
    – ab0369
    Mar 7, 2019 at 19:35

1 Answer 1

2

This is what I ended up doing. Let me know if there is better way to achieve this

string dt = 'Dec 5, 2018 3:14 PM';
        Map<String, Integer> monthMap = new Map<String, Integer>();
        monthMap.put('Jan',1);
        monthMap.put('Feb',2);
        monthMap.put('Mar',3);
        monthMap.put('Apr',4);
        monthMap.put('May',5);
        monthMap.put('Jun',6);
        monthMap.put('Jul',7);
        monthMap.put('Aug',8);
        monthMap.put('Sep',9);
        monthMap.put('Oct',10);
        monthMap.put('Nov',11);
        monthMap.put('Dec',12);

        string[] strList = dt.split(' ');
        Integer month = monthMap.get(strList[0]);
        Integer day = Integer.valueOf(strList[1].replace(',',''));
        Integer year = Integer.valueOf(strList[2]);
       string newdt = month+'/'+ day+'/'+year + ' ' + strList[3] + ' ' + strList[4];
        DateTime expected = DateTime.parse(newdt);
4
  • Sounds perfect to me. Just an addittion, if its PM you have to add +12 to your hours Mar 7, 2019 at 19:47
  • 1
    DateTime.Parse('12/5/2018 3:14 PM') should work without +12 right ?
    – ab0369
    Mar 7, 2019 at 20:43
  • 2
    You can save ~12 lines of code by making a List and then using indexOf to find the month's index. String[] monthList = ',Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','); ... Integer month = monthList.indexOf(strList[0]);
    – sfdcfox
    Mar 7, 2019 at 21:33
  • @sfdcfox good one
    – ab0369
    Mar 7, 2019 at 23:55

Not the answer you're looking for? Browse other questions tagged .