10

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

2 Answers 2

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 Commented Aug 7, 2013 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 Commented Aug 7, 2013 at 6:55
  • sorry my mistake Commented Aug 7, 2013 at 7:10
11

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
    Commented May 24, 2016 at 1:28
  • @dzh It doesn't! This was checked.
    – Ashwani
    Commented May 24, 2016 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
    Commented May 25, 2016 at 10:08

You must log in to answer this question.

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