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
-
What does the browser's console log when it tries to execute the code that doesn't work?Jordan– Jordan2012年08月09日 20:22:15 +00:00Commented Aug 9, 2012 at 20:22
-
Are you saying that you want 08/08/2012 to print as 2012年7月8日 (i.e., with the month changed from 08 to 7)?Marcelo Cantos– Marcelo Cantos2013年02月28日 00:35:46 +00:00Commented Feb 28, 2013 at 0:35
-
no, I was having a problem using a string variable vs the new Date() function.Myy– Myy2013年03月02日 17:22:42 +00:00Commented Mar 2, 2013 at 17:22
3 Answers 3
var dateString = "08/08/2012";
var d = new Date(dateString);
dateString = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
document.write(dateString);
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:
var dateString = "08/08/2012";
var d = new Date(dateString);
dateString = d.getFullYear() + "/" + ('0' + (d.getMonth()+1)).slice(-2) + "/" + ('0' + d.getDate()).slice(-2);
document.write(dateString);
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 like getFullYear() on the timestamp.
4 Comments
Date.parse doesn't work.Date.parse does work, but it doesn't return a Date object. It returns a timestamp.If all you need to do is re-order the values, you can do:
var dateString = "08/08/2012";
var dateElements = dateString.split("/");
var outputDateString = dateElements[2] + "/" + dateElements[0] + "/" + dateElements[1];
document.write(outputDateString );
Comments
I can confirm with MrSlayer that the code works in jsFiddle.
Your attempts at using Date.parse() should actuall be using Date(String(dateString)).
Don't forget to add 1 for each month.