Explain Codes LogoExplain Codes Logo

Javascript add leading zeroes to date

javascript
date-formatting
locale-specific-formatting
zero-padding
Alex KataevbyAlex Kataev·Nov 25, 2024
TLDR

When all you need is a quick solution, .padStart() is the hero you didn't know you needed:

const laurelWreath = (num) => num.toString().padStart(2, '0'); // "en garde!" to single digits const formatDate = (d) => `${d.getFullYear()}-${laurelWreath(d.getMonth() + 1)}-${laurelWreath(d.getDate())}`; console.log(formatDate(new Date())); // Stamp: "YYYY-MM-DD"; subtle, yet elegant

With laurelWreath, single-digit numbers don't stand a chance!

Dealing with locales, time, libraries and special cases

Locale-specific formatting

Dealing with global users? Date.prototype.toLocaleDateString to the rescue:

const localeFormatter = (date) => date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' // '2-digit' go forth and pad zeroes! });

This cultural chameleon adapts to locales and handles leading zeroes! For more custom results, Intl.DateTimeFormat is your guy:

const localeConfig = { year: 'numeric', month: '2-digit', day: '2-digit' }; const intlFormatter = new Intl.DateTimeFormat('en-US', localeConfig).format; console.log(intlFormatter(new Date())); // "MM/DD/YYYY"; mission accomplished!

Behold: it’s time

Dates aren't the only ones in need of zero padding, attach a cape to your time with Date.prototype.toLocaleTimeString:

const timeFormatter = (date) => date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' // Time for a zero-padding make-over });

The Mighty: Moment.js

When things get real messy, ride the Moment.js wave of relief:

const moment = require('moment'); console.log(moment(new Date()).format('YYYY-MM-DD')); // Welcome to the formatted side

Just be sure this doesn't make your performance take a nosedive. Size matters!

Temporal objects: too fast, too timeless

For dates that don't fit the norm, Temporal offers a path to salvation:

const { Temporal } = require('@js-temporal/polyfill'); const farFuture = Temporal.PlainDate.from({ year: 10000, month: 1, day: 1 }); console.log(farFuture.toString()); // "10000-01-01". Back to the future time travelers!

Now go wild and test these methods for consistency!

Mind performance, compatibility and validation

Peeking at the rear-view mirror

While native methods come with their perks, performance can take a hit. When you spot a flurry of dates, cache formatted ones.

One size fits all: Compatibility

To extend a warm embrace to every browser, use polyfills or fallbacks for not-so-veteran methods like Intl or padStart.

I've got my eyes on you: Debugging

Beware the lurking formatting gremlins; always validate and use your debugging compass to keep your formatted dates in check.