Subscribe

Vanilla JavaScript add leading zeroes to date

✍️

How to add leading zeroes to a JavaScript Date object?

30 Mar, 2020 · 2 min read

Ever wanted to convert a date in JavaScript to look something like this 01-01-2020.

Quite a pain if I may say so, Javascript has a bad understanding of the date object, and no option to have those leading zeroes.

Converting a JavaScript date object to strings

First, we need to convert the javascript date object to separate strings.

Start by creating a new date.

let date = new Date('01-01-2020');

Then let’s make the specific elements we are going to need and see what we start off with.

let day = date.getDate(); // 1
let month = date.getMonth(); // 0
let year = date.getFullYear(); // 2020

Huh? Why is the month 0? This is because JavaScript date months go from 0 to 11, so we must correct it by adding 1.

let month = date.getMonth() + 1; // 1

Adding leading zeroes to JavaScript date

To add the leading zeroes to the day and month object we have several options, but the following is the cleanest and quickest.

In any case we have to convert the integer to a string.

let date = new Date('01-01-2020');
let day = date.getDate(); // 1
day = day.toString().padStart(2, '0'); // '01'
let month = date.getMonth() + 1; // 1
month = month.toString().padStart(2, '0'); // '01'
let year = date.getFullYear(); // 2020
let newDate = day + '-' + month + '-' + year;
console.log(newDate); // '01-01-2020'

The padStart function will only work on a string, hence we first convert the integer to a string. Then the padStart will append ‘0’ to a maximum of two.

You can play around in this codepen demo.

See the Pen Vanilla JavaScript add leading zeroes to date by Chris Bongers (@rebelchris) on CodePen.

Note: padStart unfortunately has no IE compatibility. 😭

Thank you, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter