Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime to valid JavaScript date [duplicate]

Tags:

I have a datetime string being provided to me in the following format:

yyyy-MM-dd HH:mm:ss
2011-07-14 11:23:00

When attempting to parse it into a JavaScript date() object it fails. What is the best way to convert this into a format that JavaScript can understand?

The answers below suggest something like

var myDate = new Date('2011-07-14 11:23:00');

Which is what I was using. It appears this may be a browser issue. I've made a http://jsfiddle.net/czeBu/ for this. It works OK for me in Chrome. In Firefox 5.0.1 on OS X it returns Invalid Date.

like image 544
Jeremy B. Avatar asked Jul 14 '11 15:07

Jeremy B.


3 Answers

This works everywhere including Safari 5 and Firefox 5 on OS X.

UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below

var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));
console.log(date_test);

FIDDLE

like image 185
mplungjan Avatar answered Sep 30 '22 09:09

mplungjan


One can use the getmonth and getday methods to get only the date.

Here I attach my solution:

var fullDate = new Date(); console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
    twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
    twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
like image 39
Shekhar Patel Avatar answered Sep 30 '22 11:09

Shekhar Patel


Just use Date.parse() which returns a Number, then use new Date() to parse it:

var thedate = new Date(Date.parse("2011-07-14 11:23:00"));
like image 31
pimvdb Avatar answered Sep 30 '22 10:09

pimvdb