convert custom date string to date object

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)

Answers:

Answer

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.

Answer

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);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.