JavaScript: Clock


The code used for clock.js is below:


function getDateTime() {
    var now     = new Date(); 
    var year    = now.getFullYear();
    var month   = now.getMonth()+1; 
    var day     = now.getDate();
    var hour    = now.getHours();
    var minute  = now.getMinutes();
    var second  = now.getSeconds(); 
    if(month.toString().length == 1) {
         month = '0'+month;
    }
    if(day.toString().length == 1) {
         day = '0'+day;
    }   
    if(hour.toString().length == 1) {
         hour = '0'+hour;
    }
    if(minute.toString().length == 1) {
         minute = '0'+minute;
    }
    if(second.toString().length == 1) {
         second = '0'+second;
    }   
    var dateTime = month+'/'+day+'/'+year+' | Time: '+hour+':'+minute+':'+second;   
     return dateTime;
}

// example usage: realtime clock
setInterval(function(){
    currentTime = getDateTime();
    document.getElementById("clock-div").innerHTML = `Date: ${currentTime}`;
}, 1000);


The code used for index.php is below:



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../styles.css">
    <title>JavaScript: Clock</title>
</head>
<body>

<h1 class="lesson-h1">JavaScript: Clock</h1>

    <div id="clock-div" style="width: 100%; font-size: 3rem; border: solid 1px black; text-align: center;"></div>

<script src="clock.js"></script>
<?php
    include('../show_code.php');
    show_code('clock.js');
    show_code('index.php');
?>
    
</body>
</html>