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() constructor.

index.html

<!doctype html>
<html>
<body>
    <h1>JavaScript Date Example</h1>
    <p id="message"></p>
    
    <script>
        <!-- your JavaScript goes here -->
        var date = Date();
        document.getElementById("message").innerHTML = date;
    </script>
	
</body>
</html>

Get Date in Milliseconds

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

index.html

<!doctype html>
<html>
<body>
    <h1>JavaScript Date Example - Get Date in milliseconds</h1>
    <p id="message"></p>
    
    <script>
        <!-- your JavaScript goes here -->
        var date = new Date().getTime();
        document.getElementById("message").innerHTML = date;
    </script>
    
</body>
</html>

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)

Following is an example demonstrating the three Constructors mentioned above.

index.html

<!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>

Conclusion

In this JavaScript Tutorial, we learned about Date, and its constructors to set Date Object to a specific date.