This site was established about twenty days ago. That is not a very long time, after all, it has only just begun, so I thought I would write an online timer to record how long the website has been running. Enough talk—let's get started.

First, I thought of using JavaScript to define the time and then using HTML to output it. The most troublesome part is mainly the time calculation. Here is the code:

HTML Code

This site has been running steadily: <span id="htmer_time"></span>

JavaScript Code

function secondToDate(second) {
    if (!second) {
        return 0;
    }
    var time = new Array(0, 0, 0, 0, 0);
    if (second >= 365 * 24 * 3600) {
        time[0] = parseInt(second / (365 * 24 * 3600));
        second %= 365 * 24 * 3600;
    }
    if (second >= 24 * 3600) {
        time[1] = parseInt(second / (24 * 3600));
        second %= 24 * 3600;
    }
    if (second >= 3600) {
        time[2] = parseInt(second / 3600);
        second %= 3600;
    }
    if (second >= 60) {
        time[3] = parseInt(second / 60);
        second %= 60;
    }
    if (second > 0) {
        time[4] = second;
    }
    return time;
}

function setTime() {
    var create_time = Math.round(new Date(Date.UTC(2017, 04, 18, 2, 0, 0)).getTime() / 1000);
    var timestamp = Math.round((new Date().getTime() + 8 * 60 * 60 * 1000) / 1000);
    currentTime = secondToDate((timestamp - create_time));
    currentTimeHtml = currentTime[0] + '年 ' + currentTime[1] + '天 ' + currentTime[2] + '时 ' + currentTime[3] + '分 ' + currentTime[4] + '秒 ';
    document.getElementById("htmer_time").innerHTML = currentTimeHtml;
}
setInterval(setTime, 1000);

Usage Instructions

  1. Create a time.js file and write the JavaScript code into it.
  2. Place the time.js file in the website root directory (or any accessible directory—as long as you remember where it is).
  3. Reference this JavaScript file in the website header.
  4. Write the HTML code wherever you need to display the running time.