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

125
Views
How to add a preceding '0' to days and months less than 10

I am having some issues displaying data from my backend API because the incoming dates are formatted incorrectly.

Currently, day and month numbers are entered without a preceding '0' if they are less than 10. For example, 9 should be 09

All incoming dates are in this format: year/month/day.

How can I transform the dates to a format with preceding zeros for numbers less than 10?

My current code:

let date = '2021/1/31';

const addZeros = (date) => {
  const year = date.split('/')[0];
  const month = date.split('/')[1];
  const day = date.split('/')[2];

  return `${year}-${month}-${day}`;
};

console.log(addZeros(date));

Tests:

2021/9/14 --> 2021/09/14

2021/1/7 --> 2021/01/07

2021/10/17 --> 2021/10/17

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

0

You can easily achieve the result using split, map, and join.

function convertDate(str) {
  return str
    .split("/")
    .map((s) => (s < 10 ? `0${s}` : s))
    .join("/");
}

console.log(convertDate("2021/9/14")); //--> 2021/09/14
console.log(convertDate("2021/1/7")); //--> 2021/01/07
console.log(convertDate("2021/10/17")); //--> 2021/10/17

about 4 years ago · Juan Pablo Isaza Report

0

const addZeros = (date) => {
  let [year, month, day] = date.split('/');
  month = month.length == 1 ? `0${month}` : month; 
  day = day.length == 1 ? `0${day}` : day; 

  return `${year}-${month}-${day}`;
};


const test = (date, formatDate) => {
  if ( addZeros(date) == formatDate )
    console.log("Success!")
  else
    console.log(`Error: Expected: ${formatDate}, Receive: addZeros(date)`)
}

test('2021/1/31', '2021-01-31')
test('2021/11/1', '2021-11-01')
about 4 years ago · Juan Pablo Isaza Report

0

I use this simple method to add leading zeros:

function leadingZeros(n, digitsneeded)
{
 return ("00000000000" + n).substr(-digitsneeded)
}

// leadingzeros(3, 2) is "03"
// leadingzeros(12, 5) is "00012"
// leadingzeros(1234, 3) is "234" -- Be careful!

There is no need to check whether you already have the right number of digits. (However, it will truncate a "too big" number, so watch out for that.)

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!