Home > Back-end >  Conversion of date value in JavaScript
Conversion of date value in JavaScript

Time:11-25

I am getting value like 202001 and I want to covert it to January_2020.

Is there a way to convert it like this:

202001->January_2020

How can I get this update value in JavaScript?

CodePudding user response:

const dateToStr = (input) => {
    if (input.length !== 6) {
        return "wrong date syntax, use YYYYMM";
    }
    
    const parts = input.match(/([0-9]{4})([0-9]{2})/);
    if (!parts) {
        return "wrong date syntax, use YYYYMM";
    }
    
    // @TODO check syntax of parts
    
    const formatter = new Intl.DateTimeFormat('en-EN', {month: 'long'}).format;
    const formatted = formatter(new Date(Date.UTC(parseInt(parts[1]), parseInt(parts[2]) - 1)));
    return `${formatted}_${parts[1]}`;
};

console.log(
    dateToStr("202001"),  // January_2020
    dateToStr("202111"),  // November_2021
    dateToStr("202001x"), // wrong date syntax, use YYYYMM
    dateToStr("2020AC"),  // wrong date syntax, use YYYYMM
);
  • Related