How To Get Date Month And Year In Javascript

When working with web applications or projects, it is common to come across situations where you need to work with dates. JavaScript provides an in-built Date object to handle date and time operations. In this blog post, we will learn how to get the date, month, and year in JavaScript.

Getting the Current Date, Month, and Year

To get the current date, month, and year, you need to create a new instance of the Date object. Once you have the instance, you can use its in-built methods to get the desired information. Here’s how you can do that:


        // Create a new Date instance
        const currentDate = new Date();
        
        // Get the current date
        const date = currentDate.getDate();
        
        // Get the current month (0-11)
        const month = currentDate.getMonth();
        
        // Get the current year
        const year = currentDate.getFullYear();
        
        console.log(`Today's date is ${date}-${month+1}-${year}`);
    

Note that the getMonth() method returns the month value in the range of 0-11, where 0 represents January and 11 represents December. To get the correct month value, you’ll need to add 1 to the result.

Formatting the Date

Sometimes, you might want to pad the date and month with a leading zero if their value is less than 10. You can achieve this by using the following helper function:


        function padWithZero(num) {
            return num < 10 ? '0' + num : num;
        }
    

Now, you can use this function to pad the date and month with a leading zero:


        const paddedDate = padWithZero(date);
        const paddedMonth = padWithZero(month + 1);

        console.log(`Today's date is ${paddedDate}-${paddedMonth}-${year}`);
    

Conclusion

In this blog post, we learned how to get the date, month, and year in JavaScript using the Date object. We also learned how to format the date by padding it with a leading zero. Working with dates in JavaScript is simple and straightforward, making it easy for you to handle date-related operations in your web applications and projects.