JavaScript provides a variety of methods to get the current date and time, or to extract specific parts of a date. In this article, we will discuss some of the most commonly used JavaScript date methods for getting the date.
The Date Object
Before we dive into the methods, it is important to understand the Date object in JavaScript. The Date object represents a single moment in time, and can be created using the new Date()
constructor. By default, the new Date()
constructor creates a Date object representing the current date and time.
const currentDate = new Date(); // Creates a Date object representing the current date and time
Get Current Date
To get the current date, we can use the getDate()
method of the Date object. The getDate()
method returns the day of the month (from 1 to 31) for the specified date.
const currentDate = new Date();
const day = currentDate.getDate(); // Returns the day of the month (from 1 to 31)
We can also use the getMonth()
method to get the month (from 0 to 11) for the specified date. Note that the month index starts from 0, so we need to add 1 to get the actual month number.
const month = currentDate.getMonth() + 1; // Returns the month (from 0 to 11)
To get the year for the specified date, we can use the getFullYear()
method.
const year = currentDate.getFullYear(); // Returns the year (four digits)
Get Current Time
To get the current time, we can use the getTime()
method of the Date object. The getTime()
method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
const currentTime = new Date().getTime(); // Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
We can also use the getHours()
, getMinutes()
, and getSeconds()
methods to get the hours (from 0 to 23), minutes (from 0 to 59), and seconds (from 0 to 59), respectively, for the specified date.
const hours = currentDate.getHours(); // Returns the hour (from 0 to 23)
const minutes = currentDate.getMinutes(); // Returns the minutes (from 0 to 59)
const seconds = currentDate.getSeconds(); // Returns the seconds (from 0 to 59)
Get Day of the Week
To get the day of the week for the specified date, we can use the getDay()
method. The getDay()
method returns a number (from 0 to 6) representing the day of the week, where 0 represents Sunday, 1 represents Monday, and so on.
const dayOfWeek = currentDate.getDay(); // Returns the day of the week (from 0 to 6)
In this article, we discussed some of the most commonly used JavaScript date methods for getting the date. By using these methods, you can easily extract specific parts of a date and time, or get the current date and time. Remember to always test your code thoroughly to ensure it works as expected.