JavaScript Date() Constructor

The JavaScript Date() constructor either is used to create an instance of the Date or is used to get a string representing the current date and time. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>
   <p id="abc"></p>

   <script>
      const d = new Date();
      
      document.getElementById("xyz").innerHTML = d;
      document.getElementById("abc").innerHTML = d.toLocaleString();
   </script>

</body>
</html>
Output

Please note: A constructor is used to create an object whereas a method is used to execute some block of statements.

JavaScript Date() Syntax

The syntax of the Date() constructor in JavaScript is:

new Date()

where the new keyword is used to create an instance of the object.

However we can also define value, DateString, or DateObject while creating an instance of the Date() constructor. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="res"></p>

   <script>
      const d = new Date("September 16, 2022, 08:59:00");
      document.getElementById("res").innerHTML = d;
   </script>

</body>
</html>
Output

Also we can define year, month (by index number from 0 to 11), day, hours, minutes, seconds, and milliseconds while creating an instance of the Date() constructor. Keep the following points in mind while using these parameters to the Date() constructor:

    year - For 1900 to 1999, you have to use 0 to 99. And use the actual year for all other year. For example:
    • 89 for 1989
    • 2011 for 2011
    • 97 for 1997
    • 2000 for 2000
  • monthIndex - For January, you have to use 0. Similary for February, you have to use 1. That is, use 0-11 for January-December
  • day - Use an integer value from 1-31 based on the day of the month you need to use
  • hours - Legal values are from 0 to 23
  • minutes - Legal values are from 0 to 0 to 59
  • seconds - Legal values are from 0 to 59
  • milliseconds - Legal values are from 0 to 999

Please note: The last four parameters, that are hours, minutes, seconds, and milliseconds are optional. The default value of day is 1, whereas the default value of rest three parameters are 0. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>With only Required Parameters: <span id="resOne"></span></p>
   <p>With Required and an Optional Parameter: <span id="resTwo"></span></p>

   <script>
      const dOne = new Date(2022, 8);
      document.getElementById("resOne").innerHTML = dOne;

      const dTwo = new Date(2022, 8, 16);
      document.getElementById("resTwo").innerHTML = dTwo;
   </script>

</body>
</html>
Output

With only Required Parameters:

With Required and an Optional Parameter:

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋