[javascript] Convert datetime to valid JavaScript date

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.

This question is related to javascript datetime

The answer is


You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:

   moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want 

   Output: 28-Apr-1993

Hope it will help you :)


new Date("2011-07-14 11:23:00"); works fine for me.


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

You can use get methods:

_x000D_
_x000D_
var fullDate = new Date();_x000D_
console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_


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

Here I attach my solution:

_x000D_
_x000D_
var fullDate = new Date(); console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_


Use:

enter code var moment = require('moment')
var startDate = moment('2013-5-11 8:73:18', 'YYYY-M-DD HH:mm:ss')

Moment.js works very well. You can read more about it here.


function ConvertDateFromDiv(divTimeStr) {
    //eg:-divTimeStr=18/03/2013 12:53:00
    var tmstr = divTimeStr.toString().split(' '); //'21-01-2013 PM 3:20:24'
    var dt = tmstr[0].split('/');
    var str = dt[2] + "/" + dt[1] + "/" + dt[0] + " " + tmstr[1]; //+ " " + tmstr[1]//'2013/01/20 3:20:24 pm'
    var time = new Date(str);
    if (time == "Invalid Date") {
        time = new Date(divTimeStr);
    }
    return time;
}