How To Get The Day Of The Month In JavaScript

How to get the Day of the Month in JavaScript

Today we’ll look at how to get the day of the month in JavaScript. This is a frequent task that many developers need to perform, and there are some different approaches that may be used. We’ll look at each approach and see how it works.

To get the day of the month in JavaScript

The month’s day is important information we may use in several different cases. There are many ways to get the day of the month; below are the three easiest ways.

Using the getDate() function

The getDate() function returns the day of the month for the specified date in local time. It returns a number between 1 and 31.

This is the simplest and quickest method for getting the day of the month because this function is designed to do so. Simply calling the function on a date object to get the day of the month of that date object. For example:

let today = new Date();

// Use getDate() to get the day of the month
console.log(`Today is the ${today.getDate()} day of the month.`)

Output:

Today is the 26 day of the month.

Using the toLocaleDateString() function

The toLocaleDateString() function is used to get the date portion of a date object as a string. It returns a string value corresponding to the date’s portion based on locale conventions.

To get the day of the month, call toLocaleDateString() on a date object, then pass a locale format as the first argument and the option day: numeric as the second. As an example:

let today = new Date();

// Use toLocaleDateString() to get the day of the month
let dayOfMonthToday = today.toLocaleDateString('en-us', {day: "numeric"})
console.log(`Today is the ${dayOfMonthToday} day of the month.`)

Output:

Today is the 26 day of the month.

Using the getUTCDate() function

The getUTCDate() method returns the month’s date for the specified date in universal time. It returns a number between 1 and 31.

Similar to getDate(), getUTCDate() is also created to get the month’s date. The difference is that getDate() uses local time, whereas getUTCDate() uses universal time. As a result, instead of using the getDate() function, we can use the getUTCDate() function. For example:

let today = new Date();

// Use getUTCDate() to get the day of the month
console.log(`Today is the ${today.getUTCDate()} day of the month.`)

Output:

Today is the 26 day of the month.

Summary

This article helps you learn about how to get the day of the month in JavaScript. The most frequent methods are the getDate() and getUTCDate() functions. If you want to specify the locale, you can use the toLocaleDateString() function. Regardless of your function, getting the day of the month is a simple task requiring only a few lines of code.

Have a nice day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *