0
0
JavascriptHow-ToBeginner · 3 min read

How to Get Year, Month, and Day from Date in JavaScript

In JavaScript, you can get the year, month, and day from a Date object using getFullYear(), getMonth(), and getDate() methods respectively. Note that getMonth() returns a zero-based month (0 for January, 11 for December), so add 1 to get the calendar month number.
📐

Syntax

Use these methods on a Date object to get parts of the date:

  • date.getFullYear(): Returns the full year (e.g., 2024).
  • date.getMonth(): Returns the month as a number from 0 (January) to 11 (December).
  • date.getDate(): Returns the day of the month (1 to 31).

Remember to add 1 to getMonth() to get the usual month number.

javascript
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1; // Add 1 because months start at 0
const day = date.getDate();
💻

Example

This example shows how to get the year, month, and day from the current date and print them in a readable format.

javascript
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();

console.log(`Year: ${year}`);
console.log(`Month: ${month}`);
console.log(`Day: ${day}`);
Output
Year: 2024 Month: 6 Day: 15
⚠️

Common Pitfalls

A common mistake is forgetting that getMonth() returns a zero-based month, so January is 0, not 1. This can cause off-by-one errors when displaying or using the month number.

Also, getDate() returns the day of the month, not the day of the week.

javascript
const date = new Date('2024-06-15');

// Wrong: Using getMonth() directly without adding 1
const wrongMonth = date.getMonth();
console.log(`Wrong Month: ${wrongMonth}`); // Outputs 5, not 6

// Right: Add 1 to getMonth()
const correctMonth = date.getMonth() + 1;
console.log(`Correct Month: ${correctMonth}`); // Outputs 6
Output
Wrong Month: 5 Correct Month: 6
📊

Quick Reference

MethodDescriptionReturns
getFullYear()Gets the full yearNumber (e.g., 2024)
getMonth()Gets the month (zero-based)Number (0 for Jan to 11 for Dec)
getDate()Gets the day of the monthNumber (1 to 31)

Key Takeaways

Use getFullYear() to get the year from a Date object.
Add 1 to getMonth() because it returns zero-based months.
Use getDate() to get the day of the month.
Remember getMonth() zero-based indexing is a common source of bugs.
These methods work on any valid JavaScript Date object.