Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple conversion for this datetime format?

I'm retrieving data from a JSON feed using jQuery and as part of the feed I'm getting 'datetime' attributes like "2009-07-01 07:30:09". I want to put this information into a javascript Date object for easy use but I don't believe the Date object would recognize this kind of format if I simply plugged it into the constructor. Is there a function or maybe a clever trick I can use to quickly break down this format into something the Date object can recognize and use?

like image 573
Mathias Schnell Avatar asked Jul 12 '26 15:07

Mathias Schnell


2 Answers

The "date" attribute you are retrieving from that webservice is not a real Date, as it is not a recognized date format.

The easiest way to handle it as a Date object would be to replace the empty space with a "T":

var receivedDate = "2009-07-01 07:30:09";
var serializedDate = new Date(receivedDate.replace(" ", "T"));
alert(serializedDate);

This is not the most correct, as it is not handling timezones, but in most cases will work.

like image 54
Alex Bagnolini Avatar answered Jul 14 '26 06:07

Alex Bagnolini


See this and this.

input = "2009-07-01 07:30:09";
var res =  input.match(/([\d\-]+) (\d+):(\d+):(\d+)/);
date = new Date(Date.parse(res[1])); 
date.setHours(res[2]);
date.setMinutes(res[3]);
date.setSeconds(res[4]);
console.log(date);

Edit: My original answer was

t = new Date(Date.parse("2009-07-01 07:30:09"));

which did not throw any error in chrome but all the same incorrectly parsed the date. This threw me off. Date.parse indeed appears to be quite flaky and parsing the complete date and time with it is probably not very reliable.

Edit2: DateJS appears to be a good solution for when some serious parsing of text to date is needed but at 25 kb it is a bit heavy for casual use.

like image 40
anshul Avatar answered Jul 14 '26 05:07

anshul



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!