Date and Time in Javascript

The Date() object provides the number of seconds from January 1970 UTC up to the moment it is invoked. The parameters of the function allow for formatting of the output..

.toLocaleTimeString(), .toLocaleDateString() and .toLocaleString() are all methods for controlling the display.

let theDate = new Date();
// Result: Sat Mar 07 2020 10:19:08 GMT-0500 (Eastern Standard Time)

let theLocalTIme = theDate.toLocaleTimeString();
//	Result: 10:19:08 AM

let theLocalDate = theDate.toLocaleDateString();
//	Result: 3/7/2020

let theLocalBoth = theDate.toLocaleString();
//	Result:  3/7/2020, 10:19:08 AM

Time Constant Update

Constantly updating the time, like a clock would, can be achieved with a simpler setInterval()

function constantUpdate() {

    let timeHolder = document.getElementById("constant-time");

    let cntr = 0;

    setInterval(function() {


        let thisDateTime = new Date();

        let thisLocalTIme = thisDateTime.toLocaleTimeString();

        timeHolder.innerText = thisLocalTIme;
    }, 1000)
let currentTime = constantUpdate();


2:19:37 PM

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

↑ Back to Top