devhtml
devhtml

Reputation: 13

Displaying the current date time with milli seconds in html

I have added DateTime.Now in the html view. I need it to update automatically in the view.

Here's my code:

<span id="footer_clock"></span>

<script>
    setInterval(function () {           
        var now = new Date();
        var currentdateTime = now.toLocaleDateString() + " " + now.toLocaleTimeString();
        document.getElementById('footer_clock').textContent = currentdateTime;
    }, 1000);
</script>

Upvotes: 0

Views: 175

Answers (2)

Unkle Benz
Unkle Benz

Reputation: 83

Once the html page is delivered by server everything happens on the client side ... Server delivers a "copy" of the page and browser gets it, parse it, display it then runs scripts and all folks.

Then the only way to do is to set a timer with setInterval function. A common way to achieve this problem is to set a timer to "wake up" every second (but you can choose the delay). Important: delay is in millisecond.

At this moment you have 2 options: relying on user's DateTime or emulate server DateTime.

If you wanna rely on user's DateTime it's easy, in your callback function juste use JS function:

function timeNow() 
{
    console.log(Date.now());
}
setInterval(timeNow, 1000);

If you wanna emulate server DateTime you must set a base Date object:

var serverTime = <?php echo time() * 1000; ?>;
function timeNow() 
{
    serverTime += 1000;
    console.log(serverTime);
}
setInterval(timeNow, 1000);

But be careful emulating server DateTime because

  1. You won't be exactly synch. with real server DateTime
  2. You may have undesired side effects with zones

Upvotes: 0

Erez Lieberman
Erez Lieberman

Reputation: 2027

You can use it inside setInterval function - it will update the date every (n) milliseconds the number that you pass as the second arguments.

function doDate(){
 console.log(Date.now());
}
setInterval(doDate, 1000);

Upvotes: 1

Related Questions