const d = new Date();
We can get the Date and time by passing different values into the date constructor. The examples below explore how we can get the Date and time by our requirement.
const currdt = new Date(); console.log(currdt);
How to get custom date and time by different parameter
const newdt = new Date(2000, 5, 3, 11, 43, 21, 0); console.log(newdt);
How to get Date and time by a string parameter
const dt = new Date("aug 1, 2011 10:03:01"); console.log(dt);
const d = new Date(90000000); console.log(d);
Fri Jan 02 1970 06:30:00 GMT+0530 (India Standard Time)
After creating a date object, use these methods to set and get the month, day, year, hour, minute, milliseconds, seconds, etc.
- The first three letters of the weekday name.
- The first three letters of the month’s name.
- Two-digit day of the month, padded on the left a zero if required.
- Four-digit year (at least), padded on the left with zeros if needed.
The toDateString() method is very useful when we need to display a date in an html document.
const d = new Date(); console.log(d.toDateString());
Thu Mar 31 2022
const d = new Date(); console.log(d.toISOString());
Other useful methods
It has many different methods. In the below example, we show the most valuable methods.
const d = new Date(); // Methods console.log("date : ",d.getDate()); console.log("hour : ",d.getHours()); console.log("day : ",d.getDay()); console.log("month : ",d.getMonth()); console.log("minutes : ",d.getMinutes()) console.log("year :",d.getFullYear());
date : 31 hour : 15 day : 4 month : 2 minutes : 31 year : 2022
That’s it for this tutorial.