I have a string variable that holds a date that looks like this.
<script>
var value = "2014-03-24";
</script>
I want to format the string into a date that looks like this.
<script>
var formattedData = "03/24/2014";
</script>
I need to replace the "-" with "/" and move the month/day/year around. Can somebody please help me? Thanks.
-
are you trying to make it a static value or dynamicCMS_95– CMS_952014年03月25日 01:08:15 +00:00Commented Mar 25, 2014 at 1:08
-
Static, I want to change a string using javascript. Well if you mean, could the date be different everytime? Then yes, it can be.Nicolas Ward– Nicolas Ward2014年03月25日 01:08:39 +00:00Commented Mar 25, 2014 at 1:08
-
okay well first off for a static value you may want to do it like this: month + "/" + day + "/" year;CMS_95– CMS_952014年03月25日 01:13:59 +00:00Commented Mar 25, 2014 at 1:13
-
Just look at what I have. I can't change the formats.Nicolas Ward– Nicolas Ward2014年03月25日 01:15:24 +00:00Commented Mar 25, 2014 at 1:15
4 Answers 4
Try this;
var d = new Date("2014-03-24");
d.toLocaleDateString("en-US"); // "3/24/2014"
Note that the advantage here is that you can pass through different locales for different formats such as "en-GB" for the UK for instance which would give you day/month/year. And if you want it really specifically with a two-digit month;
d.toLocaleDateString("en-US", {day:'2-digit', month:'2-digit', year:'numeric'}); // "03/24/2014"
If you run into browser inconsistencies, you can also do this old-school lowest-common-denominator with;
(d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear(); // "3/24/2014"
But that won't pad your day and month with 2-digit numbers though. If you want that, you'll need to use a small pad function like this;
function padDateZ(n) { return n < 10 ? '0' + n : n.toString(); }
(padDateZ(d.getMonth()+1)) + "/" + padDateZ(d.getDate()) + "/" + d.getFullYear(); // "03/24/2014"
Comments
var formatDateString = function (unformatted) {
var parts = unformatted.split('-');
return parts[1] + '/' + parts[2] + '/' + parts[0];
};
var formattedData = formatDateString(value);
Comments
You need to make use of the split and the join function of javascript.Something like,
var date = value.split("-");
new_date = date[1]+"/"+date[2]+"/"+date[0];
console.log(new_date);
Comments
("2014-03-24").split('-').join('/')
//returns "2014/03/24"
EDIT: just re-read the question, and noticed that the month and day need to be rearranged. Whoops! Go with the other answers.