williamsandonz
williamsandonz

Reputation: 16420

How do I format a DateTime string in javascript from using slashes to using hypens?

I have an input date string in the following format:

yyyy/mm/dd

This is my desired output date string format:

yyyy-mm-dd

Is there a built-in way to do this in Javascript?

Upvotes: 9

Views: 16630

Answers (2)

DutGRIFF
DutGRIFF

Reputation: 5223

Adeneo's answer did solve this particular case but I would like to show how you can get this to any format you want. We start by getting the date that is shown as a date object by the calls new Date() ad passing it the date string:

var dateStr = "1991/01/11";
var d = new Date(dateStr);

Now we can call any of the getters listed here to get that value and build out the desired string:

var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;  //We add +1 because Jan is indexed at 0 instead of 1
var curr_year = d.getFullYear();
console.log(curr_year + "-" + curr_month + "-" + curr_date);

This allows us to build any format we want.

Upvotes: 3

adeneo
adeneo

Reputation: 318212

Use string.replace

date = date.replace(/\//g, '-');

FIDDLE

If for some reason you don't want to use a regex

date = date.split('/').join('-');

Upvotes: 15

Related Questions