Signup/Sign In

How to get day, month and year from a date object

Answer: Using date() object methods

JavaScript offers various built-in date object methods by which we can get information like date, month, year, etc. Some of the built-in date object methods are getDate() to get the date, getMonth() to get the month, getFullYear() to get the full year, etc. We will discuss each of them later in this lesson.

The getDate(), getMonth(), and getFullYear() methods return the date and time in the local timezone of the computer that the script is running on. If you want to get the date and time in the universal timezone we have to replace these methods with getUTCDate(), getUTCMonth(), and getUTCFullYear().

Getting current day

We can get the current day or date using JavaScript getDate() method. This method returns the current date in the local timezone of the computer. This method returns the integer value between 1 to 31.

Example: Using getDate() method

In the given example, we have used the getDate() method to get the current date.

<!DOCTYPE html>
<html>
<head>
	<title>Getting a current day</title>
</head>
<body>
	<script>
		var today = new Date();
		var date = today.getDate(); 
		console.log("The curren date is" + " " + date); 
	</script>
</body>
</html>

Output


The current date is 20

Getting current month

We can get the current month using the getMonth() method. This method returns the month in numbers not the name of the month. The return value of the getMonth() method range from 0 to 11 which means January is 0 and the December is 11.

Example: Using getMonth() method

In this example, we have used the getMonth() method to get the current month.

<!DOCTYPE html>
<html>
<head>
	<title>Getting a current month</title>
</head>
<body>
	<script>
		var today = new Date();
		var month = today.getDate(); 
		console.log("The current month is" + " " + month); 
	</script>
</body>
</html>

Output


The current month is 20

Getting current year

We can get the current year using the getFullYear() method. This method returns the four-digit integer value between 1000 to 9999.

Example: Using getFullYear() Method

<!DOCTYPE html>
<html>
<head>
	<title>Getting a current year</title>
</head>
<body>
	<script>
		var today = new Date();
		var year = today.getFullYear(); 
		console.log("The current year is" + " " + year);  
	</script>
</body>
</html>

Output


The current year is 2021

Conclusion

In this lesson, we have discussed how to get the current day, month, and year using JavaScript. As we know JavaScript offers several date objects method that helps us in getting the current date, month and year. So, we have used the getDate() to get the current date, used the getMonth() to get the current month, and used the getFullYear() method to get the current year.



About the author: