Explain Codes LogoExplain Codes Logo

How do I get Month and Date of JavaScript in 2 digit format?

javascript
date-formatting
javascript-regex
date-libraries
Anton ShumikhinbyAnton Shumikhin·Oct 9, 2024
TLDR

For a quick solution to get month and date in a 2-digit format in JavaScript, leverage the Date class methods and (``${}).slice(-2);` substring trick for zero padding. Here's the magic distilled into a few lines of code:

const date = new Date(); const month = (`0${date.getMonth() + 1}`).slice(-2); // cheeky trick for leading zero const day = (`0${date.getDate()}`).slice(-2); console.log(month); // displays month as "MM" console.log(day); // displays date as "DD"

This utilises getMonth() and getDate() for fetching the values, and the slice(-2) trick pads the date unit with a '0' if necessary.

In-depth: Date formatting in JavaScript

While the initial example provides a solid basis, taking a deeper dive into date formatting patterns and edge case handling will ensure the solutions are more robust.

Custom methods for date and month

Beyond built-in methods, standalone and helper functions can be a lifeline to ensure the correct date format:

  • Helper function: Why not build a helper function on our own instead of relying on the interpreter’s magical tricks? This function will give you the two-digit format if the number is already in two digits, or it’ll add a leading zero if it isn't:
function twoDigits(d) { return (d < 10 ? '0' : '') + d; // "0" or nothing, then the number. Easy as pie! } console.log(twoDigits(date.getMonth() + 1)); // "MM" console.log(twoDigits(date.getDate())); // "DD"

Handling potential formatting pitfalls

In JavaScript dates, we can encounter some potential pitfalls when formatting:

  • Be sure to use getFullYear() instead of getYear(). The getYear() method is deprecated and can cause unforeseen issues:
const year = date.getFullYear(); // Trust me on this, don't use getYear(), just don't.
  • Remember, getMonth() returns a range from 0-11, so we have to add 1 to reflect the actual month number:
const month = (`0${date.getMonth() + 1}`).slice(-2); // JavaScript starts counting months from 0 because... reasons.
  • Sometimes we have to display the date in "YYYY-MM-DD" format, so watch out for the toISOString method that returns a string in ISO format but includes the time, which we don’t need here. We can replace 'T' with a blank space to give a "YYYY-MM-DD HH:mm:ss" format:
const formattedDate = date.toISOString().replace('T', ' '); // It'll give you pilot's connectivity, without the pilot. console.log(formattedDate); // "YYYY-MM-DD HH:mm:ss"

Time to become a time-bender with date libraries

In case you require more refined date handling, I'd recommend you taking the help of some well-equipped date libraries out there like Moment.js or date-fns:

import format from 'date-fns/format'; const wellFormattedDate = format(new Date(), "MM/dd/yyyy"); // Can actually format the date as good as Dave at the office! console.log(wellFormattedDate); // "MM/DD/YYYY"

All-in-one date formatting

With JavaScript, we can get really creative and format the full date-time string by combining various methods, while injecting a dash of JavaScript regex magic:

const fullDateTime = `${year}-${month}-${day} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; console.log(fullDateTime); // "YYYY-MM-DD HH:mm:ss", more alpha-numeric than a license plate

Or manage to format using a date library:

import { format } from 'date-fns'; const comprehensiveFormattedDate = format(new Date(), 'yyyy-MM-dd HH:mm:ss'); console.log(comprehensiveFormattedDate); // "YYYY-MM-DD HH:mm:ss"

These were a couple of tricks out of JavaScript's seemingly bottomless magic hat 🎩✨. So next time your front end demands well-formatted dates, JavaScript’s got you covered!