JavaScript : Get Date Methods

In JavaScript, the Date object provides several methods for retrieving various components of a date and time. These methods allow you to extract information such as the year, month, day, hour, minute, second, and millisecond from a Date object. Here are the commonly used methods to get date components:

1. getFullYear()


Returns the year (four digits) of the specified date according to local time.


let date = new Date();
let year = date.getFullYear();
console.log(year); // Example output: 2022

 

2. getMonth()


Returns the month (0-11) of the specified date according to local time.


let date = new Date();
let month = date.getMonth(); // Note: January is 0, February is 1, ..., December is 11
console.log(month); // Example output: 3 (for April)

 

3. getDate()


Returns the day of the month (1-31) for the specified date according to local time.


let date = new Date();
let dayOfMonth = date.getDate();
console.log(dayOfMonth); // Example output: 14

 

4. getDay()


Returns the day of the week (0-6) for the specified date according to local time (0 for Sunday, 1 for Monday, ..., 6 for Saturday).


let date = new Date();
let dayOfWeek = date.getDay();
console.log(dayOfWeek); // Example output: 4 (for Thursday)

 

 5. getHours()


Returns the hour (0-23) of the specified date according to local time.


let date = new Date();
let hour = date.getHours();
console.log(hour); // Example output: 10 (for 10 AM)

 

6. getMinutes()


Returns the minutes (0-59) of the specified date according to local time.


let date = new Date();
let minutes = date.getMinutes();
console.log(minutes); // Example output: 30

 

7. getSeconds()


Returns the seconds (0-59) of the specified date according to local time.

let date = new Date();
let seconds = date.getSeconds();
console.log(seconds); // Example output: 15

 

8. getMilliseconds()


Returns the milliseconds (0-999) of the specified date according to local time.


let date = new Date();
let milliseconds = date.getMilliseconds();
console.log(milliseconds); // Example output: 123

 

These methods provide a convenient way to retrieve various components of a date and time from a Date object in JavaScript, allowing you to perform date-related operations in your applications.