Show time spent in years, days, minutes and seconds using Moment.js

For the homepage of this blog, I wanted to show a timer which shows the number of years/days/minutes & seconds spent since I started working. This blog post is tutorial on how to do that.

Firstly you will need to download and include moment.js. Here is a fiddle you can play around which and below is the code for your refrence.


<div>Time spent making websites</div>
<div id="timer">


$(document).ready(function () {
    // this function is only used so that I can use the .format() function in this example.
    if (!String.prototype.format) {
        String.prototype.format = function () {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function (match, number) {
                return typeof args[number] != 'undefined' ? args[number] : match;

    window.setInterval(function () {
    }, 1000);


function refreshTimer() {
    var now = moment();
    var start = moment([2010, 12, 22]);
    var years = now.diff(start, 'years');
    var days = now.diff(start, 'days');
    var hours = now.diff(start, 'hours');
    var minutes = now.diff(start, 'minutes');
    var seconds = now.diff(start, 'seconds');
    $("#timer").html("<span id='years'>{0} years</span><span id='days'>{1} days</span><span id='hours'>{2} hours</span><span id='minutes'>{3} minutes</span><span id='seconds'>{4} seconds</span>".format(years, days, hours, minutes, seconds));


#timer span {margin-right:10px;}