I'm trying to display a clock that updates every second (e.g. 1/5/2015 12:05:01 then 1/5/2015 12:05:02, etc.) using moment.js.
I found previous solutions to my question (see Dynamic date and time with moment js and setinterval), however it doesn't work with the newest version of moment.js (v2.11.0). The solution provided uses v2.6.
Can someone advise?
it seems to work fine for me. For the same code. And only the moment.min.js pointed to v2.11.0
Have a look at the code(credits: to MilkyWayJoe)-
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 fiddle with v2.11.0 - JSFiddle Demo
A working compact solution.
JSFiddle
HTML
<div id="datetime"></div>
JavaScript
var update = function() {
document.getElementById("datetime")
.innerHTML = moment().format('MMMM Do YYYY, h:mm:ss a');
}
setInterval(update, 1000);
The previous solution you mentioned does work for moment.js v2.11.0.
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);
});
See JSFiddle
However the JSFiddle in that accepted answer with the previous solution does not work giving the following error.
"Refused to execute script from 'https://raw.github.com/timrwood/moment/1.6.2/moment.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled."
It can be fixed by simply loading the script from a proper CDN like so:
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.min.js