Had an interesting request to add a clock to a web page yesterday. Turned out to be a bit more difficult than we thought. We used moment.js for this project. It’s a VERY cool javascript library that helps you with time. If you’ve never done work with javascript and time consider yourself lucky. It’s downright hard. Moment.js takes the guesswork out – although there’s a little bit of a learning curve. Let’s get started.
First, add a div to your page and give it an id.
Now, we add our script in the footer of the html.
//call jquery and moment.js libraries http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js //function to create clock functionality. updates every second. function timedUpdate() { showClock(); setTimeout(timedUpdate, 1000); } //moment.js function. get current time > pass to moment function > create html function showClock() { var now = new Date().getTime(); var test = moment(now).format('MMMM Do YYYY, h:mm:ss a'); //create html $("#clock").html(test); } //call update timedUpdate();
And then you get a nice clock to work with.
http://www.inhifistereo.com/wp-content/uploads/2014/02/Clock.html