Home > Enterprise >  How to format MM/YYYY to YYYY-MM in js
How to format MM/YYYY to YYYY-MM in js

Time:10-01

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 ?

CodePudding user response:

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>

CodePudding user response:

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);

CodePudding user response:

Please use Array.map(), Array.split() and Array.reverse() functions.

Like this.

const date = "3/2020";
const result = date.split('/').map(val => val.length === 1 ? '0'   val : val).reverse().join('-');
    
console.log(result);

CodePudding user response:

It can be done with a one-liner (which I have broken down into multiple lines to explain them) :

const date = "3/2020";

const dateFormatted = date 
                        .split("/") // [ "3" , "2020" ]
                        .reverse()  // [ "2020" , "3" ]
                        .map(d => /^\d$/.test(d) ? "0"  d : d) // transforms "3" into "03" but leaves "2020" intact
                        .join("-"); // "2020-03"

console.log(dateFormatted)

CodePudding user response:

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));

CodePudding user response:

I would never claim this is a clever way of doing it but, just for fun, you could manage everything using just String.prototype.slice() in a template string:

const input1 = '3/2020';
const output1 = `${(input1).slice(-4)}-${('0'   input1).slice(-7, -5)}`;
//-----------------------------------------^ prepend a '0' in case months < 10

const input2 = '11/2020';
const output2 = `${(input2).slice(-4)}-${('0'   input2).slice(-7, -5)}`;

// test
console.log(output1);
console.log(output2);

Obviously this works exclusively on the premises that you know for sure the input string format is consistent and predictable: 1 or 2 digits for the month, 1 separator character, 4 digits for the year.
I do not recommend using it in a real product, especially if the input string comes from an API and its format may change over time.

  • Related