Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date string conversion

I have a system that returns a JSON object that contains dates in string format.

These dates are in the format "2012-10-19 06:05:38 GMT" (no... I'm stuck with them like this)

So I need to get this into a date object (d) ready to output as d.toLocaleDateString()

In chrome it works perfectly by just passing the string to a new Date (Bad bad Chrome - makes Eric lazy), but of course it fails in FF and IE

I can fix it by splitting the string but its not pretty and I've not figured out dealing with the offsets from GMT.

There must be a more elegant way...?

I'm sure someone here can do it in one line.

like image 641
Eric T Avatar asked Dec 03 '25 12:12

Eric T


2 Answers

It's not quite a one-liner, but if you know all your dates will be GMT, something like the following should work:

function parseDate(dateString) {
    // [y, m, d, hr, min, sec]
    var parts = dateString.match(/\d+/g);

    // Months are 0-indexed
    parts[1] -= 1;

    return new Date(Date.UTC.apply(Date, parts));
}
like image 55
dfreeman Avatar answered Dec 06 '25 04:12

dfreeman


If I were you, and had access to the serverside script gathering that information (and outputting it) I would convert the date into a unix timestamp, and then make Javascript process that using the Date constructor easily.

EDIT: You can use strtotime() function to convert the string date into numeric unix timestamp if you're using PHP.

like image 24
inhan Avatar answered Dec 06 '25 03:12

inhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!