-5

Given a date string in yyyy-MM-dd format like 2018-08-09, how would I convert it to yyyy/MM/dd format (2018/08/09) and dd/MM/yyyy format (09/08/2018) in javascript?

I have seen How to format a JavaScript date but it is about how to format a javascript date while i want to format a javascript date string

newbie
  • 11
  • 3

1 Answers1

1

To replace all the hyphens in the date String with slashes, you can split the String on "-" and join it on "/".

var dateStr = "2018-08-09";
var newDateStr = dateStr.split('-').join('/');//output is 2018/08/09
console.log(newDateStr);

To change a date String from yyyy-MM-dd format to dd/MM/yyyy format, you can split the String on "-", reverse it, and join it on "/".

 var dateStr = "2018-08-09";
var newDateStr = dateStr.split('-').reverse().join('/');//output is 09/08/2018
console.log(newDateStr);
iota
  • 34,586
  • 7
  • 32
  • 51