Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
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 ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!