### Install timeago.js Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents Install the timeago.js library using npm. This is the first step before importing and using it in your project. ```sh npm install timeago.js ``` -------------------------------- ### Setup HTML for Real-time Updates Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md Prepare HTML elements with a 'datetime' attribute to be updated by timeago.js. ```html

Posted:

``` -------------------------------- ### Quick Example of timeago.js Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/README.md Demonstrates simple date formatting, real-time DOM updates, and custom language registration using the timeago.js library. ```typescript import { format, render, cancel, register } from 'timeago.js'; // Simple formatting format(Date.now() - 3600000); // "1 hour ago" format('2024-06-20', 'zh_CN'); // "3 天前" // Real-time DOM updates const nodes = document.querySelectorAll('.timestamp'); render(nodes, 'en_US'); // ... auto-updates as time passes ... cancel(); // Stop updates // Custom language register('my-lang', (diff, idx) => { return [['just now', 'right now'], ...][idx]; }); format(date, 'my-lang'); ``` -------------------------------- ### Example TimerPool Structure Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/05-types.md Illustrates the internal structure of the TimerPool, showing how timer IDs generated by setTimeout are stored as keys. ```typescript { 123456789: 0, // timerId -> placeholder (always 0) 234567890: 0, // ... } ``` -------------------------------- ### Example Opts Usage Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/05-types.md Demonstrates how to create and use an Opts object to customize date formatting with a specific reference date and minimum update interval for rendering. ```typescript const opts: Opts = { relativeDate: '2020-01-01', minInterval: 5 }; format('2020-06-15', 'en_US', opts); // Computes diff from 2020-01-01 instead of now render(nodes, 'en_US', opts); // DOM updates at least every 5 seconds ``` -------------------------------- ### Initialize and Render All Time Elements Source: https://github.com/hustcc/timeago.js/blob/master/site/demo.html Initializes the timeago rendering for all elements with the '.example time' selector. This function should be called to start the automatic updating of timestamps. ```javascript function start_render_all() { timeago.render(document.querySelectorAll('.example time')); } ``` -------------------------------- ### HTML Structure with Render Example Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/02-render.md Shows the required HTML structure for elements to be rendered by timeago.js, including the 'datetime' attribute and a script to initialize the rendering. ```html

Posted:

``` -------------------------------- ### Example LocaleMap Structure Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/05-types.md Illustrates the expected structure of a LocaleMap object, showing how different locale keys are mapped to their formatter functions. ```typescript { 'en_us': (diff, idx, totalSec) => [...], 'zh_cn': (diff, idx, totalSec) => [...], // ... more locales } ``` -------------------------------- ### Example Custom Locale Function (en_US) Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/05-types.md An example implementation of a custom locale function for English (US), demonstrating how to format time differences into 'just now', 'X units ago', or 'in X units' strings. ```typescript const en_US: LocaleFunc = (diff, idx) => { const units = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year']; if (idx === 0) return ['just now', 'right now']; let unit = units[Math.floor(idx / 2)]; if (diff > 1) unit += 's'; return [`${diff} ${unit} ago`, `in ${diff} ${unit}`]; }; ``` -------------------------------- ### Registering Custom Languages Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents Provides a guide on how to register custom language dictionaries for new locales. ```APIDOC ## Register Custom Language ### Description Register your own language dictionaries to support custom locales. ### Example ```javascript // Define a custom locale dictionary var customLocaleDict = function(number, index) { // number: the timeago / timein number // index: the index of the array below return [ ['just now', 'a while'], ['%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]; }; var timeagoInstance = timeago(); // Register the custom locale timeagoInstance.register('test_local', customLocaleDict); // Use the custom locale for formatting var formattedDate = timeagoInstance.format('2016-06-12', 'test_local'); console.log(formattedDate); ``` ``` -------------------------------- ### Format Using Timestamp Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents Format a date using a timestamp. This example demonstrates formatting a date that is several hours in the past. ```js timeago().format(new Date().getTime() - 11 * 1000 * 60 * 60); // will get '11 hours ago' ``` -------------------------------- ### Start Rendering with Minimum Interval Source: https://github.com/hustcc/timeago.js/blob/master/site/demo.html Renders a single time element with a minimum update interval of 3 seconds. This is useful for scenarios where frequent updates are needed but resource usage should be managed. ```javascript function start_minint() { timeago.render(document.querySelector('.minint.single'), 'en_US', { minInterval: 3 }); } ``` -------------------------------- ### Example Relative Time Formats Source: https://github.com/hustcc/timeago.js/blob/master/README.md Illustrates various relative time formats that timeago.js can generate, from 'just now' to years ago, and 'in' statements for future times. ```plain just now 12 seconds ago 2 hours ago 3 days ago 3 weeks ago 2 years ago in 12 seconds in 3 minutes in 24 days in 6 months ``` -------------------------------- ### Selective Cancellation Example Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/03-cancel.md Demonstrates how to cancel updates for a specific element while others continue to update. This allows for fine-grained control over real-time updates. ```typescript import { render, cancel } from 'timeago.js'; const nodes = document.querySelectorAll('.timeago'); render(nodes, 'en_US'); // Cancel only the first element cancel(nodes[0]); // Other elements continue updating ``` -------------------------------- ### Start Vietnamese Locale Rendering Source: https://github.com/hustcc/timeago.js/blob/master/site/demo.html Renders a single time element using the Vietnamese locale. Ensure the 'vi' locale is loaded or available before calling this function. ```javascript function start_vi() { timeago.render(document.querySelector('.vi.single'), 'vi'); } ``` -------------------------------- ### React Integration with Timeago.js Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/02-render.md Example of integrating timeago.js into a React component using useEffect for rendering and cleanup. It ensures timers are cancelled when the component unmounts. ```typescript import { useEffect } from 'react'; import { render, cancel } from 'timeago.js'; export function TimeAgo({ date }) { const ref = useRef(null); useEffect(() => { if (ref.current) { render(ref.current, 'en_US'); return () => cancel(ref.current); } }, []); return