ArticleZip > Javascript Add Leading Zeroes To Date

Javascript Add Leading Zeroes To Date

Have you ever needed to format a date in JavaScript and found yourself wishing for those leading zeroes in the month and day? Fear not, because I'm here to guide you through a simple and effective way to add those leading zeroes to your date strings!

To begin, it's essential to understand that JavaScript doesn't automatically add leading zeroes to dates. However, with a bit of clever coding, you can easily achieve this desired format.

First off, let's start with obtaining the current date. In JavaScript, you can create a new Date object to get the current date and time. Here's a quick snippet to do just that:

Javascript

const currentDate = new Date();

Next, let's create a function that will add the leading zeroes to the month and day values of our date. This function will take the date object as an argument and return a formatted date string. Check out the code snippet below:

Javascript

function formatWithLeadingZeroes(date) {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();

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

// Usage
const formattedDate = formatWithLeadingZeroes(currentDate);
console.log(formattedDate);

In this function, we use the `padStart()` method to add leading zeroes to the day and month values. The 2 inside `padStart(2, '0')` ensures that we pad the number with zeroes to achieve a length of 2 characters.

Now, when you call `formatWithLeadingZeroes(currentDate)`, you will get your date string with leading zeroes on the day and month values in the format `YYYY-MM-DD`.

But what if you have a specific date string that you need to format with leading zeroes? Fear not, here's a quick modification to the function that handles this scenario:

Javascript

function formatCustomDateWithLeadingZeroes(dateString) {
    const dateParts = dateString.split('-');
    const month = String(Number(dateParts[1])).padStart(2, '0');
    const day = String(Number(dateParts[2])).padStart(2, '0');
    const year = dateParts[0];

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

// Usage
const customDateString = '2022-5-7';
const formattedCustomDate = formatCustomDateWithLeadingZeroes(customDateString);
console.log(formattedCustomDate);

Here, we split the custom date string into its parts and then pad the month and day values with leading zeroes as required. This way, you can easily format any date string to include those leading zeroes.

By following these simple steps and utilizing the provided code snippets, you'll be able to effortlessly add leading zeroes to your date strings in JavaScript. Say goodbye to those messy date formats and hello to clean and consistent date representations with leading zeroes!