Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active September 11, 2023 05:10
Show Gist options
  • Save adactio/ccca5710152e77fb26b4a4df0ea8fc1e to your computer and use it in GitHub Desktop.
Save adactio/ccca5710152e77fb26b4a4df0ea8fc1e to your computer and use it in GitHub Desktop.

Revisions

  1. adactio revised this gist Aug 7, 2023. 1 changed file with 1 addition and 6 deletions.
    7 changes: 1 addition & 6 deletions updateDateTimes.js
    Original file line number Diff line number Diff line change
    @@ -18,12 +18,7 @@
    'minute' : 1000 * 60,
    'second' : 1000
    };
    var unit;
    var then;
    var now;
    var diff;
    var amount;
    var text;
    var unit, then, now, diff, amount, text;
    var updateDatetimes = function () {
    now = Date.now();
    doc.querySelectorAll('time[datetime]').forEach(function(timeElement) {
  2. adactio revised this gist Aug 5, 2023. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions updateDateTimes.js
    Original file line number Diff line number Diff line change
    @@ -40,5 +40,6 @@
    timeElement.innerText = text;
    });
    };
    // Run the update every 30 seconds
    setInterval(updateDatetimes, units.second * 30);
    }(this, this.document));
  3. adactio created this gist Aug 5, 2023.
    44 changes: 44 additions & 0 deletions updateDateTimes.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    (function (win, doc) {
    'use strict';
    if (!doc.querySelectorAll || !win.Intl || !win.Intl.RelativeTimeFormat) {
    // doesn't cut the mustard.
    return;
    }
    var rtf = new Intl.RelativeTimeFormat('en', {
    localeMatcher: 'best fit',
    numeric: 'always',
    style: 'long'
    });
    var units = {
    'year' : 1000 * 24 * 60 * 60 * 365,
    'month' : 1000 * 24 * 60 * 60 * (365/12),
    'week' : 1000 * 24 * 60 * 60 * 7,
    'day' : 1000 * 24 * 60 * 60,
    'hour' : 1000 * 60 * 60,
    'minute' : 1000 * 60,
    'second' : 1000
    };
    var unit;
    var then;
    var now;
    var diff;
    var amount;
    var text;
    var updateDatetimes = function () {
    now = Date.now();
    doc.querySelectorAll('time[datetime]').forEach(function(timeElement) {
    text = 'just now';
    then = timeElement.getAttribute('datetime');
    diff = new Date(then) - new Date(now);
    for (unit in units) {
    amount = units[unit];
    if (Math.abs(diff) > amount) {
    text = rtf.format(Math.round(diff / amount), unit);
    break;
    }
    }
    timeElement.innerText = text;
    });
    };
    setInterval(updateDatetimes, units.second * 30);
    }(this, this.document));