JavaScript Date

JavaScript provides Date class to work with Date and its components.

Simple Date Example

To fetch the current system date, use Date() class with no arguments to the constructor. Following example demonstrates the use of Date().

var date = Date();
Try Online

Try Online

Get Date in Milliseconds

To fetch the current system date in milliseconds (counted from 1st Jan, 1970), use Date().getTime(). Following  is an example :

var date = new Date().getTime();
Try Online

Try Online

Initialize to a specific Date

You may also initialize the Date object with a specific date using one of the following constructors.

new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Try Online

Following is an example demonstrating the three Constructors.

<!doctype html>
<html>
<body>
	<h1>JavaScript Date Constructors Example</h1>
	<p id="message"></p>

	<script>
	<!-- your JavaScript goes here -->
      var msg = "";
      
      var date1 = new Date(1516993680832);
      var date2 = new Date("Thu Sep 24 2020 14:41:22 GMT+0530 (IST)");
      var date3 = new Date(2014, 6, 5, 15, 22, 56, 256);
      
      msg += "date1 : ";
      msg += date1;
      msg += "<br>";
      
      msg += "date2 : ";
      msg += date2;
      msg += "<br>";
      
      date.setTime(1516993680832);
      
      msg += "date3 : ";
      msg += date3;
      msg += "<br>";
      
      document.getElementById("message").innerHTML = msg;
      
	</script>
	
</body>
</html>
Try Online

Try Online

Conclusion

In this JavaScript Tutorial, we have learnt about Date, its constructors to set Date Object to a specific date. In our next tutorials we shall learn about Date Formats and Date Methods.