javascripttimetimeago

Twitter-style time-ago formatting ("2h") with Javascript


Timeago.js does a great job of formatting time stamps relative to the current time ("about 2 hours ago").

Are there any solutions that accomplish the same thing, but abbreviated? IE "2h", like Twitter uses.


Solution

  • You can use Timeago.js and overwrite the local time formatting with the abbreviated version, e.g.

    var locale = function(number, index, total_sec) {
      return [
        ['just now', 'right now'],
        ['%s s ago', 'in %s s'],
        ['1 m ago', 'in 1 m'],
        ['%s m ago', 'in %s m'],
        ['1 h ago', 'in 1 h'],
        ['%s h ago', 'in %s h'],
        ....
      ][index];
    };
    
    timeago.register('pt_ABBR', locale);
    var timeagoInstance = timeago();
    
    // then you can use it
    timeagoInstance.format(1473245023718, 'pt_ABBR');