Loading

Date in JavaScript

  • In JavaScript, you can work with dates using the built-in Date object. The Date object provides methods and properties for working with dates and times.

The Date constructor in JavaScript provides several ways to create a Date object:

  1. Date()
  2. Date(milliseconds)
  3. Date(dateString)
  4. Date(year, month, day, hours, minutes, seconds, milliseconds)

Date():

  • We can create a Date object representing the current date and time by calling the Date constructor without any arguments:

Syntax:

const currentDate = new Date();

Example:

<html>

<body>
  Current Date and Time: <span id="txt"></span>
  <script>
    var today = new Date();
    document.getElementById('txt').innerHTML = today;  
  </script>
</body>

</html>

Output:

Current Date and Time: Sun Oct 29 2023 13:21:34 GMT+0530 (India Standard Time)


Date(milliseconds):

  • You can create a Date object by specifying the number of milliseconds

Syntax:

const timestamp = 1635480000000; // Represents October 29, 2021
const dateFromTimestamp = new Date(timestamp);

Date(dateString):

  • You can create a Date object by passing a date string as an argument to the constructor.

Syntax:

const dateString = "2023-10-29T12:00:00";
const dateFromString = new Date(dateString);

Date(year, month, day, hours, minutes, seconds, milliseconds):

You can create a Date object by passing the year, month (0-based), day, hour, minute, and second as arguments to the constructor:

Syntax:

const specificDate = new Date(2023, 4, 15, 12, 30, 0); // May 15, 2023, 12:30:00

  print current time:

Example:  

<html>

<body>
  Current Time: <span id="txt"></span>
  <script>
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
  </script>
</body>

</html>

Output:

Current Time: 13:24:50


Digital clock:

Example:

Current Time: <span id="txt"></span> 
<script>  
  window.onload = function () { getTime(); }
  function getTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    // add a zero in front of numbers<10  
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
    setTimeout(function () { getTime() }, 1000);
  }
  //setInterval("getTime()",1000);//another way  
  function checkTime(i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  } 

Output:

Current Time: 13:29:19