Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format MM/YYYY to YYYY-MM in js

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 ?

like image 456
NewProgrammer Avatar asked Dec 31 '25 16:12

NewProgrammer


2 Answers

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>
like image 112
PEPEGA Avatar answered Jan 02 '26 05:01

PEPEGA


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);
like image 42
Józef Podlecki Avatar answered Jan 02 '26 04:01

Józef Podlecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!