9

How can i convert a string like this Wed Aug 07 04:30:00 GMT 2013 to a dateTime value?

11
Map <String, Integer> monthNames = new Map <String, Integer> {'Jan'=>1, 'Feb'=>2, 'Mar'=>3, 'Apr'=>4, 'May'=>5, 'Jun'=>6, 'Jul'=>7, 'Aug'=>8, 'Sep'=>9, 'Oct'=>10, 'Nov'=>11, 'Dec'=>12};
List <String> stringParts = 'Wed Aug 07 04:30:00 GMT 2013'.split(' ');
List <String> timeParts = stringParts[3].split(':');

DateTime yourDateVariable = DateTime.newInstanceGmt(Integer.valueOf(stringParts[5]), monthNames.get(stringParts[1]), Integer.valueOf(stringParts[2]), Integer.valueOf(timeParts[0]), Integer.valueOf(timeParts[1]), Integer.valueOf(timeParts[2]));
3
  • not working any other suggestion Aug 7 '13 at 6:41
  • I just executed the above code in the developer console and this is the result - 16:53:54:420 USER_DEBUG [6]|DEBUG|----------2013-08-07 04:30:00 Aug 7 '13 at 6:55
  • sorry my mistake Aug 7 '13 at 7:10
10

Use DateTime parse method: e.g.;

Datetime dt = DateTime.parse('10/14/2011 11:46 AM');

will return date instance of String.

or try

String stringDate = '2013-10-05 20:03:20';

Datetime myDate = datetime.valueOf(stringDate);
3
  • 2
    The first example gives: System.TypeException: Invalid date/time: 10/14/2011 11:46 AM
    – dzh
    May 24 '16 at 1:28
  • @dzh It doesn't! This was checked.
    – Ashwani
    May 24 '16 at 5:20
  • 2
    I think it parses based on user locale. I think my locale is set to use 24-hour time format.
    – dzh
    May 25 '16 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.