I’m trying to convert a date in javascript from MM/dd/yyyy to yyyy/MM/dd
so this works:
var d = new Date("08/08/2012");
dateString = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
document.write(dateString);
output = 2012/7/8
///////////////////////////////////////////////////
this does not:
var dateString = "08/08/2012";
var d = new Date(dateString);
dateString = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
document.write(dateString);
and neither does this:
var dateString = "08/08/2012";
var d = Date.parse(dateString);
dateString = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
document.write(dateString);
how do I make it work with a string variable? thanks
~Myy
That should, and does, work. Keep in mind that JavaScript stores months as a zero-indexed value.
If you want to have leading zeros, then you’ll have to do some magic:
jsFiddle
The reason why your
Date.parse( )example is not working, is because that function returns a timestamp (number of milliseconds since 1970), instead of a Date object. Therefore, you can’t call functions likegetFullYear()on the timestamp.