Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js: how to update the time every minute?

I'm using moment.js to display time on my webpage. I have the html div:

<div id="time"></div>

and the following javascript:

<script>
    moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');                                                                         
    var newYork = moment.tz("America/New_York").format('HH:mm a');
    $('#time').append( "Current time in New York: "+newYork );
</script>

When I run the page, it gives me the correct time, but it doesn't change with every minute, so even after 10 minutes or so I get the time that was visible when I loaded the page. Is there any way to keep the time updated? Here's my fiddle so far: http://jsfiddle.net/93pEd/132/

like image 505
randomuser1 Avatar asked Jan 08 '23 10:01

randomuser1


1 Answers

Use setInterval() to run the code every 60 seconds.

Use html() instead of append() so that the previous time is overridden.

function updateTime(){
    var newYork = moment.tz("America/New_York").format('HH:mm a');
   $('#time').html( "Current time in New York: "+newYork );
};

moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');                                                                         

updateTime();
setInterval(function(){
   updateTime();
},60000);

http://jsfiddle.net/93pEd/135/


Heres an example using seconds also:

http://jsfiddle.net/93pEd/136/

like image 108
Curtis Avatar answered Jan 20 '23 16:01

Curtis