jQuery: pass string variable to date object

user2571510 picture user2571510 · Mar 5, 2014 · Viewed 68.5k times · Source

I have a page with a number of variables that contain a date in string format (yyyy-mm-dd) which originates from using moment.js.

Is there a way I can pass such a variable to a Javascript date object resp. to convert it to a Javascript date object ? I am not interested in the time so as long as I can get the date converted to a date object that would be great.

I tried the following but this doesn't work and I couldn't find a way using moment.js:

var newVar = new Date(dateVar);

Many thanks for any help with this, Tim.

Answer

Deepak Sharma picture Deepak Sharma · Mar 5, 2014

first of all i will say following should work for you..

var dateVar = "2010-10-30";
var d=new Date(dateVar);

if you say above not working check the below one -

var dateVar = "2010-10-30";
var dsplit = dateVar.split("-");
var d=new Date(dsplit[0],dsplit[1]-1,dsplit[2]);

for the proof check the jsfiddle.. both is working fine.. JSFiddle