I have this string:
var date = "3/2020";
I need the date in this format and adding a 0 if the month is less than 10:
var result = "2020-03";
I already did this:
var date = "3/2020";
var result = date.replace('/', '-');
console.log(result);
I just need a little help to know how could I add a 0 if the month is less than 10, and to change the order. Any Suggestion ?
I would suggest looking into moment.js Then you can create a new date and set format and also set the wanted output format
const date = moment("3/2020", "MM/YYYY").format("YYYY-MM")
const date2 = moment("11/2020", "MM/YYYY").format("YYYY-MM")
console.log(date)
console.log(date2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Regex would help.
const input = "3/2020";
const [_, month, year] = /(\d+)\/(\d*)/.exec(input);
const output =`${year}-${month.toString().padStart(2, "0")}`;
console.log(output);
var date = "3/2020";
dateandmonth = date.split("/");
var event1 = new Date();
event1.setMonth(dateandmonth[0]-1);
event1.setYear(dateandmonth[1]);
MyDateString = (event1.getFullYear() + "-" + ('0' + (event1.getMonth()+1)).slice(-2));