2

How can I convert a string representation of a date to a real javascript date object?

the date has the following format

E MMM dd HH:mm:ss Z yyyy

e.g.

Sat Jun 30 00:00:00 CEST 2012

Thanks in advance

EDIT: My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)

Luke94
  • 712
  • 5
  • 14

2 Answers2

6

Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.

A simple solution thus might be :

var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);

If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :

var replacements = {
    "ACDT": "+1030",
    "CEST": "+0200",
    ... 
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);

This might be a good list of time zone abbreviation.

drunken bot
  • 486
  • 3
  • 8
0

You can use following code to convert string into datetime:

var sDate = "01/09/2013 01:10:59";
 var dateArray = sDate.split('/');
 var day = dateArray[1];

 // Attention! JavaScript consider months in the range 0 - 11
 var month = dateArray[0] - 1;
 var year = dateArray[2].split(' ')[0];
 var hour = (dateArray[2].split(' ')[1]).split(':')[0];
 var minute = (dateArray[2].split(' ')[1]).split(':')[1];
 var objDt = new Date(year, month, day, hour, minute);
 alert(objDt);
Sanjeev Rai
  • 6,721
  • 4
  • 23
  • 33