JavaScript program to display the current Day and Time

In this program, we will print the system's current day and time in the format of a 'day of weeks' hours: minute: second 'pm or am'.

getDay() is a method of date() object, it will return the current day of weeks in integer form between 0 to 6: Where 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

similarly, getHours() is a method of date and it will return current hours in integer from 0 to 23. but below the given program, we have converted it into 12 hours clock i.e hour%12.

getMinutes() will return the minute of the current system time in integer from 0 to 59. 

getSeconds()will return the current system second in integer from 0 to 59.


<!DOCTYPE html>
<html>

<body>
  <h1>Day and time in javascript</h1>
  <script>
    const date = new Date();

    // it will return days name in number from 0 to 6
    var dayweek = date.getDay();

    // days name in word.
    var dayword = ['Sunday', 'Monday', 'Tuesday',
      'Wednesday', 'Thursday', 'Friday', 'Saturday'];

    // get current day name
    var day = dayword[dayweek];

    // get hour minute and second
    var [hour, minutes, seconds] = [date.getHours(), date.getMinutes(),
    date.getSeconds()];

    // check whether am or pm
    var ampm = hour >= 12 ? 'PM' : 'AM';

    // convert hours in 12 clock format
    hour = hour % 12;

    var time = day + ' ' + hour + ":" + minutes + ":" + seconds + " " + ampm;
    document.write("<h2>format in 'day of week' hour : minute : second</h2></br>");
    document.write("Current Day and Time:", time);
  </script>
</body>

</html>

output

JavaScript program to display the current Day and Time

display current day and time using HTML form and javascript


<!DOCTYPE html>
<html>

<body>
  <script>
    function dayTime() {
      const date = new Date();

      // it will return days name in number from 0 to 6
      var dayweek = date.getDay();

      // days name in word.
      var dayword = ['Sunday', 'Monday', 'Tuesday',
        'Wednesday', 'Thursday', 'Friday', 'Saturday'];

      // get current day of week
      var day = dayword[dayweek];

      // get hour, minute, and second
      var [hour, minutes, seconds] = [date.getHours(), date.getMinutes(),
      date.getSeconds()];

      // check whether am or pm
      var ampm = hour >= 12 ? 'PM' : 'AM';

      // convert hours in 12 clock format
      hour = hour % 12;

      var time = day + ' ' + hour + ":" + minutes + ":" + seconds + " " + ampm;
      document.getElementById("dayTimeValue").innerHTML = time;
    }
  </script>

  <h1>Day and time in javascript</h1>
  <h2>format in 'day of week' hour : minute : second</h2>
  <form>
    <input type="button" value="day and time" onclick="dayTime()">
    <p id="dayTimeValue">system date time</p>
  </form>
</body>

</html>