JavaScript provides a number of ways to work with dates and times.
In this tutorial, you will learn about JavaScript Date Methods.
Let's explore
The new Date()
Method
This method creates a new Date object with the current date and time.
As an example:
const currentDate = new Date();
console.log(currentDate);
The Date.parse(dateString)
Method
This method parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
As an example:
const dateStr = "March 31, 2023";
const milliseconds = Date.parse(dateStr);
console.log(milliseconds);
The Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
Method
This method returns the number of milliseconds between January 1, 1970, 00:00:00 UTC and the specified date and time.
As an example:
const milliseconds = Date.UTC(2023, 2, 31, 21, 45, 0);
console.log(milliseconds);
The Date.now()
Method
This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
As an example:
const now = Date.now();
console.log(now);
The dateObject.getFullYear()
Method
This method returns the year of the specified date according to local time.
As an example:
const date = new Date("2023-03-31T13:59:00");
const year = date.getFullYear();
console.log(year);
The dateObject.getMonth()
Method
This method returns the month of the specified date according to local time. Note that January is 0, February is 1, and so on.
As an example:
const date = new Date("2023-03-31T13:59:00");
const month = date.getMonth();
console.log(month);
The dateObject.getDate()
Method
This method returns the day of the month for the specified date according to local time.
As an example:
const date = new Date("2023-03-31T13:59:00");
const day = date.getDate();
console.log(day);
The dateObject.getDay()
Method
This method returns the day of the week for the specified date according to local time.
- Note that Sunday is 0, Monday is 1, and so on.
As an example:
const date = new Date("2023-03-31T13:59:00");
const dayOfWeek = date.getDay();
console.log(dayOfWeek);
The dateObject.getHours()
Method
This method returns the hour of the specified date according to local time.
As an example:
const date = new Date("2023-03-31T13:59:00");
const hours = date.getHours();
console.log(hours);
The dateObject.getMinutes()
Method
This method returns the minutes of the specified date according to local time.
As an example:
const date = new Date("2023-03-31T13:59:00");
const minutes = date.getMinutes();
console.log(minutes);
The dateObject.getSeconds()
Method
This method returns the seconds of the specified date according to local time.
As an example:
const date = new Date("2023-03-31T13:59:30");
const seconds = date.getSeconds();
console.log(seconds);
The dateObject.getMilliseconds()
Method
This method returns the milliseconds of the specified date according to local time.
As an example:
const date = new Date("2023-03-31T13:59:30.123");
const milliseconds = date.getMilliseconds();
console.log(milliseconds);