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:

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 »