timeago.js

repository·master·Indexed 26 days ago

https://github.com/hustcc/timeago.js

A lightweight library (< 2kb) for formatting dates into human-readable relative time strings such as '3 hours ago' or 'in 12 seconds'. It supports internationalization (i18n), real-time DOM rendering via the render() and cancel() functions, and works in both Node.js and browser environments. Version 4.1.0.

Tokens
2.3K
Snippets
9
Records
17
Agent score
88%

What's inside timeago.js

  1. Import timeago.js

    master

    If using a module bundler, import the specific functions you need. If using a <script> tag in HTML, the library is available via the global timeago variable.

    import { format, render, cancel, register } from 'timeago.js';
    <script src="dist/timeago.min.js"></script>
  2. Real-time DOM rendering with render() and cancel()

    master

    You can automatically render relative time in DOM elements that have a datetime attribute. This enables real-time updates.

    Setup HTML: Elements must have a datetime attribute containing a date string.

    <div class="timeago" datetime="2016-06-30 09:20:00"></div>

    API:

    • render(dom[, locale = 'en_US', opts]): Starts real-time rendering for the provided DOM nodes.
    • cancel([dom]): Stops real-time rendering. If no argument is provided, it cancels all tasks. If a node is provided, it cancels only for that node.

    Options (opts):

    • relativeDate: The relative date to compare against.
    • minInterval: The minimum update interval in seconds for real-time rendering.
    import { render, cancel } from 'timeago.js';
    
    const nodes = document.querySelectorAll('.timeago');
    
    // use render method to render nodes in real time
    render(nodes, 'zh_CN');
    
    // render with opts
    // render(nodes, 'en_US', { minInterval: 3 });
    
    // cancel all real-time render task
    cancel();
    
    // or cancel for the specific one
    cancel(nodes[0]);
  3. Format a date with format()

    master

    The format function converts a Date instance, timestamp, or date string into a human-readable relative time string (e.g., '3 hours ago').

    Signature: format(date[, locale = 'en_US', opts])

    Parameters:

    • date: A Date instance, timestamp (number), or date string.
    • locale: (Optional) The locale string (e.g., 'en_US', 'zh_CN'). Defaults to 'en_US'.
    • opts: (Optional) Configuration object.
    import { format } from 'timeago.js';
    
    // format timestamp
    format(1544666010224);
    
    // format date instance
    format(new Date(1544666010224));
    
    // format date string
    format('2018-12-12');
    
    // format with locale
    format(1544666010224, 'zh_CN');
    
    // format with locale and relative date
    format(1544666010224, 'zh_CN', { relativeDate: '2018-11-11' });
  4. Register a custom locale with register()

    master

    You can add support for new languages by providing a locale function to register.

    Signature: register(locale, localeFunc)

    Locale Function Signature: (number: number, index: number, totalSec: number) => [string, string]

    • number: The timeago / timein number.
    • index: The index of the array returned by the function.
    • totalSec: Total seconds between the formatted date and today's date.
    • Return Value: A tuple [string, string] where the first element is the 'ago' format and the second is the 'in' format.
    import { register, format } from 'timeago.js';
    
    const localeFunc = (number: number, index: number, totalSec: number): [string, string] => {
      return [
        ['just now', 'right now'],
        ['%s seconds ago', 'in %s seconds'],
        ['1 minute ago', 'in 1 minute'],
        ['%s minutes ago', 'in %s minutes'],
        ['1 hour ago', 'in 1 hour'],
        ['%s hours ago', 'in %s hours'],
        ['1 day ago', 'in 1 day'],
        ['%s days ago', 'in %s days'],
        ['1 week ago', 'in 1 week'],
        ['%s weeks ago', 'in %s weeks'],
        ['1 month ago', 'in 1 month'],
        ['%s months ago', 'in %s months'],
        ['1 year ago', 'in 1 year'],
        ['%s years ago', 'in %s years']
      ][index];
    };
    
    // register your locale with timeago
    register('my-locale', localeFunc);
    
    // use it
    format('2016-06-12', 'my-locale');
  5. Render real-time relative time in DOM elements with render()

    master
    Use render() to automatically update the text content of one or more DOM elements with a relative time string (e.g., "5 minutes ago") that refreshes periodically. The function reads the timestamp from a data-date attribute on the provided element(s).