How To Display Current Date And Time Using Javascript

admin_img Posted By Bajarangi soft , Posted On 01-02-2021

The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date().

How To Display Current Date And Time Using Javascript

In this example, you will learn to write a JavaScript program that will display the current date.

Example : Display Current Date

// program to display the date
// get local machine date time
const date = new Date();

// get the date as a string
const n = date.toDateString();

// get the time as a string
const time = date.toLocaleTimeString();

// display date
console.log('Date: ' + n);

// display time

console.log('Time: ' + time);

 

Output

Date: Wed Aug 26 2020
Time: 1:13:12 PM

Step 1:Create Blade file like date.balde.php and make javascript code for getting today date and time. 
resources/views/date.blade.php.

 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="keywords" content="HTML5 Template" />
<meta name="viewport" content=" width=device-width, initial-scale=1, maximum-scale=1" />
<title></title>

<link rel="shortcut icon" href="images/favicon.png" />

<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,300;0,400;0,700;0,900;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
</head>
<body>
    </style>
    <!--page start-->
    <div class="page">
        <br><br>
        <div class="col-md-3">
            <span style="color: cadetblue">Today Date and Time is : </span> <span align="center" id="p1"  style="color: brown"></span>
        </div>

    </div><!-- page end -->

    <script type="text/javascript">3

      function formatAMPM(date) {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        return strTime;
      }

      const monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"];
      const dateObj = new Date();
      const month = monthNames[dateObj.getMonth()];
      const day = String(dateObj.getDate()).padStart(2, '0');
      const year = dateObj.getFullYear();
      const output = day  + '\n'+ month  + ',' + year;

      var time = formatAMPM(new Date);

      var dateTime = output+' '+time;
      
      document.getElementById("p1").innerHTML = dateTime;
    </script>

</body>
</html>

Related Post