Categories: Development

Live time and date with vanilla Javascript

A live and active time and date with vanilla Javascript.

CodePen example.

Start by setting variables for the date string:

var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;

Month is plus 1 because January is represented as 0, Febuary as 1 etc when in normal systems January is 1, Febuary is 2.

Now the current time function. This sets the HTML element #time to the browser time with toLocaleTimeString. Click the link to see formating options.

function theTime() {
    var d = new Date();
    document.getElementById("time").innerHTML = d.toLocaleTimeString("en-US");
}

Make the days and months value a two digit string. 1 becomes 01, 5 will become 05 etc:

if (day < 10) {
    day = appendZero(day);
}

if (month < 10) {
    month = appendZero(month);
}

The today date string as day/month/year which is then assigned to the #date element.

Then finally the time function being refreshed every seconds thanks to setInterval.

today = day + "/" + month + "/" + today.getFullYear();

document.getElementById("date").innerHTML = today;

var myVar = setInterval(function () {
    theTime();
}, 1000);

The HTML:

<div class="container">
  <div class="row text-center">
    <div class="col-12">
      <div class="card">
        <h1 id="time" class="time"></h1>
        <h1 id="date" class="date"></h1>
      </div>
    </div>
  </div>
</div>

 

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago