Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic date and time with moment.js and setInterval

I'm trying to find out how I can display dynamic date and time using moment.js.

Apparently I can't figure out to use setInterval properly.

If possible I'd prefer not to use jQuery as moment.js dosn't need it.

Here's what I have so far: http://jsfiddle.net/37fLF/2/.

$(document).ready(function () {
    var datetime = $('#datetime'),
        date = moment(new Date()),
        update = function(){
            datetime.html(date.format('dddd, MMMM Do YYYY, h:mm:ss a'));
        };
    update();
    setInterval(update, 1000);
});​
like image 317
bchr Avatar asked May 14 '12 20:05

bchr


1 Answers

I've made a few modifications in your code:

Note that the method update is now outside the ready event handler

code:

var datetime = null,
        date = null;

var update = function () {
    date = moment(new Date())
    datetime.html(date.format('dddd, MMMM Do YYYY, h:mm:ss a'));
};

$(document).ready(function(){
    datetime = $('#datetime')
    update();
    setInterval(update, 1000);
});

working demo: jsfiddle

like image 91
MilkyWayJoe Avatar answered Oct 21 '22 18:10

MilkyWayJoe