### 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 ;
}
```
--------------------------------
### Start Single Native Time Rendering
Source: https://github.com/hustcc/timeago.js/blob/master/site/demo.html
Renders a single time element using the native locale. This is useful for testing specific elements or when a default locale is desired.
```javascript
function start_single_native() {
timeago.render(document.querySelector('.native .single', 'zh_CN'));
}
```
--------------------------------
### Registering Custom Locales in timeago.js
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/08-locales.md
Provides an example of defining and registering a custom locale function with timeago.js. This allows for custom language support.
```typescript
import { register, format } from 'timeago.js';
// Define your locale
const myLocale = (diff, idx) => {
const templates = [
['just now', 'right now'],
['%s seconds ago', 'in %s seconds'],
// ... 12 more entries
];
return templates[idx];
};
// Register it
register('my-custom', myLocale);
// Use it
format(date, 'my-custom');
```
--------------------------------
### Browser Global Usage
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
When timeago.js is included via a script tag, all exports are available on the global `timeago` object. This example shows basic usage of format, render, and cancel.
```html
```
--------------------------------
### Register a Short Format Locale
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/04-register.md
Register a locale that uses abbreviated units for a more compact output. This is ideal for UIs where space is limited. The example shows how to use single letters for units and append 'a' for past times.
```typescript
register('en-short', (diff, idx) => {
const units = ['s', 'm', 'h', 'd', 'w', 'M', 'y'];
if (idx === 0) return ['now', 'now'];
return [
`${diff}${units[Math.floor(idx / 2)]}a`,
`in ${diff}${units[Math.floor(idx / 2)]}`
];
});
format(Date.now() - 2 * 60 * 60 * 1000, 'en-short');
// Returns: "2ha" (2 hours ago)
```
--------------------------------
### Main Entry Point Imports
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Demonstrates how to import the core functions (format, render, cancel, register) from the timeago.js library using both CommonJS and ES Module syntax.
```APIDOC
## Default Import (CommonJS)
```typescript
const { format, render, cancel, register } = require('timeago.js');
```
## ES Module Import
```typescript
import { format, render, cancel, register } from 'timeago.js';
```
```
--------------------------------
### Basic Usage
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Shows how to instantiate the timeago class and format a date string into a relative time statement.
```APIDOC
## Basic Usage
### Description
Instantiate the `timeago` class and use the `format` method to convert a date string into a relative time string.
### Code
```javascript
var timeagoInstance = timeago();
var formattedDate = timeagoInstance.format('2016-06-12');
console.log(formattedDate); // Example output: '2 years ago'
```
```
--------------------------------
### Importing timeago.js
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Demonstrates how to import the timeago.js library using ES6 modules or CommonJS, and how to include it via a script tag in HTML.
```APIDOC
## Importing timeago.js
### Description
Import the library using ES6 style or CommonJS, or include it directly in HTML.
### Usage
**ES6 Style:**
```javascript
import timeago from 'timeago.js';
```
**CommonJS:**
```javascript
var timeago = require("timeago.js");
```
**HTML Script Tag:**
```html
```
```
--------------------------------
### Import Full Build
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/06-configuration.md
Import the full build to pre-register all 57 locales. This is useful when you need access to all locales without manual registration.
```typescript
import { format } from 'timeago.js/lib/full';
```
```typescript
import { format } from 'timeago.js/esm/full';
```
--------------------------------
### Using Full Build Locales
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/08-locales.md
Demonstrates using the full build of timeago.js, which pre-registers all available locales. This is suitable when all locales are needed.
```typescript
import { format } from 'timeago.js/lib/full';
// All 57 locales pre-registered
format(date, 'de'); // ✓ Works
format(date, 'ja'); // ✓ Works
format(date, 'vi'); // ✓ Works
```
--------------------------------
### Opts
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/05-types.md
Configuration options for the `format()` and `render()` functions.
```APIDOC
## Opts
Configuration options for `format()` and `render()`.
```typescript
type Opts = {
readonly relativeDate?: TDate;
readonly minInterval?: number;
};
```
### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `relativeDate` | `TDate` | Current time | Alternative reference date for relative calculations |
| `minInterval` | `number` | `1` | Minimum seconds between real-time DOM updates (only for `render()`) |
Both properties are `readonly`, enforcing immutability.
### Used By
- `format(date: TDate, locale?: string, opts?: Opts)`
- `render(nodes: ..., locale?: string, opts?: Opts)`
- Passed to `diffSec()` and `run()` internally
### Example
```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
```
```
--------------------------------
### Using Timestamps
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Demonstrates how to use JavaScript timestamps (milliseconds since epoch) with the `format` method.
```APIDOC
## Using Timestamp
### Description
Format dates using JavaScript timestamps (milliseconds since the Unix Epoch).
### Code
```javascript
// Example: Format a date that was 11 hours ago from the current time
var timestamp = new Date().getTime() - 11 * 1000 * 60 * 60;
var formattedDate = timeago().format(timestamp);
console.log(formattedDate); // Output: '11 hours ago'
```
```
--------------------------------
### Importing Types from timeago.js
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/05-types.md
Shows how to import all type definitions from the main 'timeago.js' entry point or specific types from subpaths.
```typescript
// From 'timeago.js'
import type { TDate, LocaleFunc, LocaleMap, Opts, TimerPool } from 'timeago.js';
// Also available from subpath
import type { TDate } from 'timeago.js/lib/interface';
import type { TDate } from 'timeago.js/esm/interface';
```
--------------------------------
### Full Build Import
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Illustrates how to import the full build of timeago.js, which includes all locale functions pre-registered.
```APIDOC
## Full Build (`src/full.ts`)
Includes all locale functions pre-registered:
```typescript
import { format, render, cancel, register } from 'timeago.js/lib/full';
import { format, render, cancel, register } from 'timeago.js/esm/full';
```
Exports:
- All items from main module
- All 57 locales automatically registered
```
--------------------------------
### File Organization Structure
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/00-index.md
Illustrates the directory structure of the timeago.js project, highlighting the purpose of key files and directories.
```tree
src/
├── format.ts # Main formatting function
├── realtime.ts # Real-time DOM updates
├── register.ts # Locale registration
├── interface.ts # Type definitions
├── full.ts # Full build with all locales
├── index.ts # Main entry point
├── utils/
│ ├── date.ts # Date parsing & formatting
│ └── dom.ts # DOM utilities
└── lang/ # 57 language locales
├── en_US.ts
├── zh_CN.ts
└── ... (55 more)
```
--------------------------------
### Global Variable Usage in Browser
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/06-configuration.md
When loaded via a script tag, timeago.js is available as a global `timeago` object in the browser. This example demonstrates formatting a date using the global object.
```html
```
--------------------------------
### TypeScript Usage with timeago.js
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Demonstrates importing and using core timeago.js functions like format, render, cancel, and register in a TypeScript environment. Shows type annotations for dates, options, and locale functions.
```typescript
import { format, render, cancel, register } from 'timeago.js';
import type { Opts, TDate, LocaleFunc } from 'timeago.js';
const date: TDate = '2024-06-20';
const opts: Opts = { minInterval: 5 };
const result: string = format(date, 'en_US', opts);
const localeFn: LocaleFunc = (diff, idx) => {
return ['just now', 'right now'];
};
register('my-locale', localeFn);
```
--------------------------------
### Read datetime attribute from DOM element
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/07-utilities.md
Reads the 'datetime' attribute from a given HTMLElement. Returns an empty string if the attribute is not present. Used by the render function to get the date for formatting.
```typescript
function getDateAttribute(node: HTMLElement): string
```
```html
```
```typescript
const elem = document.querySelector('.timeago');
getDateAttribute(elem);
```
--------------------------------
### Import Core Build
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/06-configuration.md
Use the default export for the core build, which includes 'en_US' and 'zh_CN' locales.
```typescript
import { format } from 'timeago.js';
```
--------------------------------
### Package.json Exports Field Configuration
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Defines the entry points for different module systems and environments, enabling conditional exports for optimized module resolution.
```json
{
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"unpkg": "dist/timeago.min.js",
"browser": "dist/timeago.min.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./lib/*": {
"import": "./dist/esm/*.js",
"require": "./dist/lib/*.js"
},
"./esm/*": {
"import": "./dist/esm/*.js"
}
}
}
```
--------------------------------
### Using Core Build Locales
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/08-locales.md
Shows how to use the core build of timeago.js, which includes only 'en_US' and 'zh_CN' for minimal size. Other locales will fall back to 'en_US'.
```typescript
import { format } from 'timeago.js';
// Only en_US and zh_CN available (< 2 KB)
format(date, 'en_US'); // ✓ Works
format(date, 'zh_CN'); // ✓ Works
format(date, 'fr'); // ✗ Falls back to en_US
```
--------------------------------
### Import Main Entry
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/00-index.md
Import the main functions from timeago.js, which includes en_US and zh_CN locales by default.
```typescript
import { format, render, cancel, register } from 'timeago.js';
```
--------------------------------
### Module Organization - Core Modules
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/10-architecture.md
Illustrates the directory structure of the timeago.js core modules, including the main entry point, formatting functions, real-time rendering, locale registration, and utility files.
```treeview
src/
├── index.ts # Main entry point (exports public API)
├── full.ts # Full build with all locales pre-registered
├── format.ts # Main formatting function
├── realtime.ts # Real-time DOM rendering & cancellation
├── register.ts # Locale registration system
├── interface.ts # Type definitions
├── utils/
│ ├── date.ts # Date parsing & formatting utilities
│ └── dom.ts # DOM attribute access utilities
└── lang/ # Locale implementations (57 languages)
├── en_US.ts
├── zh_CN.ts
├── ja.ts
└── ... (54 more)
```
--------------------------------
### Format Path Data Flow
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/10-architecture.md
Illustrates the sequence of operations for formatting a date into a human-readable string, from user input to final output.
```text
User Input
↓
format(date, locale, opts)
↓
toSd(date) [normalize to Date instance]
↓
diffSec(date, opts) [calculate seconds difference]
↓
getLocale(locale) [retrieve locale function]
↓
formatDiff(diff, localeFunc) [apply locale formatting]
↓
String Output (e.g., "3 hours ago")
```
--------------------------------
### Importing All ES Modules
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Use this pattern to import all modules when using ES modules.
```typescript
import from 'timeago.js/esm/*'
```
--------------------------------
### Type Definitions Import
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Shows how to import type definitions for use with TypeScript.
```APIDOC
## Type Definitions
```typescript
import type { TDate, LocaleFunc, LocaleMap, Opts, TimerPool } from 'timeago.js';
```
```
--------------------------------
### Localization
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Explains how to set and change the locale for date formatting, with support for 'en' (default) and 'zh_CN'.
```APIDOC
## Localization
### Description
Set the locale for date formatting. The library supports 'en' (default) and 'zh_CN'. You can also set the locale during instantiation or using `setLocale`.
### Usage
**Setting locale during instantiation:**
```javascript
var timeagoInstance = timeago(null, 'zh_CN');
var formattedDate = timeagoInstance.format('2016-06-12');
```
**Setting locale using `setLocale`:**
```javascript
var timeagoInstance = timeago();
timeagoInstance.setLocale('zh_CN');
var formattedDate = timeagoInstance.format('2016-06-12');
```
```
--------------------------------
### Basic Usage of timeago.js
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Instantiate the timeago class and use the format method to convert a date string into a relative time string.
```js
var timeago = timeago();
timeago.format('2016-06-12')
```
--------------------------------
### Import Full Version of timeago.js
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/04-register.md
Import the full version of timeago.js to include all pre-registered locales. This is an alternative to manually registering each locale.
```typescript
import { format, register } from 'timeago.js/lib/full';
// or
import { format, register } from 'timeago.js/esm/full';
```
--------------------------------
### Importing All CommonJS Modules
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Use this pattern to import all modules when using CommonJS.
```typescript
require('timeago.js/lib/*')
```
--------------------------------
### Include Timeago.js via CDN
Source: https://github.com/hustcc/timeago.js/blob/master/README.md
Use this script tag to include the timeago.js library directly from a CDN. This method reflects the latest version upon publication to npm.
```html
```
--------------------------------
### Manual Locale Registration with timeago.js
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/08-locales.md
Explains how to manually register locales using the 'register' function for tree-shaking purposes. Imported locales are then available for use.
```typescript
import { format, register } from 'timeago.js';
import fr from 'timeago.js/lib/fr';
import ja from 'timeago.js/lib/ja';
register('fr', fr);
register('ja', ja);
format(date, 'fr'); // ✓ Works
format(date, 'ja'); // ✓ Works
format(date, 'de'); // ✗ Falls back to en_US
```
--------------------------------
### render(nodes, locale, opts)
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md
Renders and automatically updates DOM elements containing date information. Elements must have a `datetime` attribute.
```APIDOC
## render(nodes, locale, opts)
### Description
Renders and sets up auto-updating relative time strings for a collection of DOM nodes. Each node must have a `datetime` attribute specifying the date.
### Parameters
#### Path Parameters
- **nodes** (NodeList | HTMLElement[]) - Required - A list of DOM nodes to render.
- **locale** (string) - Optional - The locale to use for formatting. Defaults to 'en'.
- **opts** (object) - Optional - An options object for advanced configuration.
### Options
- **minInterval** (number) - Minimum seconds between DOM updates. Defaults to 5.
### HTML Datetime Attribute
Elements must have a `datetime` attribute with a valid date format (ISO string, Unix timestamp, etc.).
```html
```
### Example
```javascript
timeago.render(document.querySelectorAll('.timeago'))
```
```
--------------------------------
### Browser Script Tag for UMD Build
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Include the timeago.js library in a web page using a script tag, either from a CDN or a local file.
```html
```
--------------------------------
### Importing Locales with CommonJS and ES Modules
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Shows how to import locale files for timeago.js using both CommonJS `require` syntax and ES Module `import` syntax, followed by registering them with the library.
```typescript
// CommonJS require
const ja = require('timeago.js/lib/ja');
const fr = require('timeago.js/lib/fr');
// ES module
import ja from 'timeago.js/lib/ja';
import fr from 'timeago.js/esm/fr';
// Both are equivalent LocaleFunc implementations
register('ja', ja);
register('fr', fr);
```
--------------------------------
### Importing Date Formatting Utilities
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Access internal date formatting utilities via subpath imports for advanced usage.
```typescript
import {
toDate,
formatDiff,
diffSec,
nextInterval
} from 'timeago.js/lib/date';
```
--------------------------------
### Format Function Input: ISO String
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md
The `format` function accepts ISO 8601 formatted date and datetime strings.
```typescript
format('2024-06-20')
```
```typescript
format('2024-06-20T10:30:00')
```
--------------------------------
### Import timeago.js (ES6 and CommonJS)
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Import the timeago.js library into your project using ES6 import syntax or CommonJS require. This makes the timeago object globally available.
```js
import timeago from 'timeago.js';
// or
var timeago = require("timeago.js");
```
--------------------------------
### Set Locale Using setLocale Method
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Change the locale of an existing timeago instance using the `setLocale` method. This allows dynamic switching of languages.
```js
timeago().setLocale('zh_CN');
```
--------------------------------
### Import Specific Locale for Tree-Shaking
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/06-configuration.md
Import specific locales and register them manually for better tree-shaking. This approach is recommended when you only need a subset of the available locales.
```typescript
import { format, register } from 'timeago.js';
import ja from 'timeago.js/lib/ja';
```
```typescript
// or
import ja from 'timeago.js/esm/ja';
```
```typescript
register('ja', ja);
```
--------------------------------
### Locale Registration and Retrieval
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/10-architecture.md
Explains how locales are registered with the library and how they are retrieved for formatting, including fallback mechanisms.
```text
register(locale, func)
↓
Locales[locale.toLowerCase()] = func
getLocale(locale)
↓
Return Locales[(locale || 'en_us').toLowerCase()]
↓
Fallback to Locales.en_us if not found
```
--------------------------------
### Register a Locale with Context-Aware Behavior
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/04-register.md
Register a locale that can adapt its output based on additional context, such as `totalSec`. This allows for more nuanced formatting, like distinguishing between 'prior' and 'hence' for time differences.
```typescript
register('formal', (diff, idx, totalSec) => {
if (idx === 0) {
return ['At this very moment', 'Very shortly'];
}
const templates = [
['%s seconds prior', '%s seconds hence'],
['%s minutes prior', '%s minutes hence'],
['%s hours prior', '%s hours hence'],
['%s days prior', '%s days hence'],
['%s weeks prior', '%s weeks hence'],
['%s months prior', '%s months hence'],
['%s years prior', '%s years hence']
];
return templates[Math.floor(idx / 2)];
});
```
--------------------------------
### Full Build Import (ES Module)
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Import the full build for ES Module environments when all locales are needed and pre-registered. This version includes all locale functions.
```typescript
import { format, render, cancel, register } from 'timeago.js/esm/full';
```
--------------------------------
### Load timeago.js with ES6 import
Source: https://github.com/hustcc/timeago.js/blob/master/site/index.html
Import the timeago.js library in your ES6-compatible JavaScript project.
```javascript
import * as timeago from 'timeago.js';
```
--------------------------------
### Public Exports - Main Module
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Lists the symbols exported by the main module (`src/index.ts`) and their corresponding types and descriptions.
```APIDOC
## Public Exports - Main Module (`src/index.ts`)
Exports the following to consumers:
| Symbol | Type | Module | Description |
|--------|------|--------|-------------|
| `format` | function | `src/format.ts` | Format a date to relative time string |
| `render` | function | `src/realtime.ts` | Render DOM with real-time updates |
| `cancel` | function | `src/realtime.ts` | Cancel real-time updates |
| `register` | function | `src/register.ts` | Register a custom locale |
| `TDate` | type | `src/interface.ts` | Date input union type |
| `LocaleFunc` | type | `src/interface.ts` | Locale formatter function type |
| `LocaleMap` | type | `src/interface.ts` | Locale map record type |
| `Opts` | type | `src/interface.ts` | Options object type |
| `TimerPool` | type | `src/interface.ts` | Timer tracking object type |
```
--------------------------------
### Full Build Import (CommonJS)
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Import the full build for CommonJS environments when all locales are needed and pre-registered. This version includes all locale functions.
```typescript
import { format, render, cancel, register } from 'timeago.js/lib/full';
```
--------------------------------
### Importing Type Definitions
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Import type definitions for better TypeScript integration.
```typescript
import type from 'timeago.js'
```
--------------------------------
### Main Module Exports
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
This shows the exports from the main module, typically found in 'src/index.ts'. It includes core formatting, real-time rendering, and locale registration functionalities.
```typescript
export { format } from './format';
export { render, cancel } from './realtime';
export { register };
export * from './interface';
```
--------------------------------
### Re-render with Different Locale
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/02-render.md
Demonstrates re-rendering elements with a new locale. Calling render() again on existing elements clears their old timers and sets up new ones.
```typescript
const nodes = document.querySelectorAll('.timeago');
// Initial render
render(nodes, 'en_US');
// Later, change language
render(nodes, 'ja'); // Clears old timers and sets up new ones
```
--------------------------------
### Real-time Rendering Path Data Flow
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/10-architecture.md
Details the process for rendering and continuously updating timeago strings within DOM elements, including scheduling and DOM manipulation.
```text
User calls render(nodes, locale, opts)
↓
Normalize input to HTMLElement[]
↓
For each node:
├── getDateAttribute(node) [read datetime attribute]
├── run(node, date, localeFunc, opts)
│ ├── diffSec() [calculate current diff]
│ ├── formatDiff() [get display string]
│ ├── node.innerText = result [update DOM]
│ ├── nextInterval() [calculate next update time]
│ └── setTimeout(run, interval) [schedule next update]
├── setTimerId(node, timerId) [store timer ID on element]
└── TIMER_POOL[timerId] = 0 [track in global pool]
```
--------------------------------
### Importing DOM Utilities
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Access internal DOM utilities via subpath imports for advanced usage.
```typescript
import {
getDateAttribute,
setTimerId,
getTimerId
} from 'timeago.js/lib/dom';
```
--------------------------------
### Include timeago.js via Script Tag
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Include the timeago.js library in your HTML file using a script tag to make it available globally.
```html
```
--------------------------------
### Setting Relative Date
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Explains how to set a specific date to be used as the reference point for relative time calculations, instead of the current date.
```APIDOC
## Setting Relative Date
### Description
Initialize `timeago` with a specific date to serve as the reference point for formatting.
### Code
```javascript
// Set '2016-06-10 12:12:12' as the reference date
var timeagoInstance = timeago('2016-06-10 12:12:12');
// Format a date relative to the set reference date
var formattedDate = timeagoInstance.format('2016-06-12', 'zh_CN');
console.log(formattedDate); // Example output depends on locale and reference date
```
```
--------------------------------
### Importing Specific Locales (ES Modules)
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Import specific locale modules for ES module environments to enable tree-shaking.
```typescript
import ja from 'timeago.js/lib/ja';
import fr from 'timeago.js/esm/fr';
```
--------------------------------
### Browser Usage: Script Tag and Formatting
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md
Include the timeago.js script via a CDN and use the global `timeago` object to format dates directly in your browser JavaScript.
```html
```
--------------------------------
### Main Exports from timeago.js
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md
Imports the core functions and types from the timeago.js library. These are the primary tools for formatting dates and managing real-time updates.
```typescript
import {
format,
render,
cancel,
register,
TDate,
LocaleFunc,
Opts
} from 'timeago.js';
```
--------------------------------
### Render with Custom Update Interval
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/02-render.md
Renders elements with a minimum update interval in seconds. This is useful for performance optimization, especially with many elements.
```typescript
render(nodes, 'en_US', { minInterval: 10 });
// DOM updates at least every 10 seconds
```
--------------------------------
### register()
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/00-index.md
Registers a new custom locale function for use with the `format()` and `render()` functions.
```APIDOC
## register()
### Description
Registers a new custom locale function for use with the `format()` and `render()` functions.
### Method
function
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **localeName** (string) - Required - The name of the locale to register (e.g., 'my-lang').
- **localeFunc** (LocaleFunc) - Required - The function that defines the locale's timeago strings.
### Request Example
```javascript
import { register, format } from 'timeago.js';
register('my-lang', (diff, idx) => {
return [
['just now', 'right now'],
// ... 12 more entries for each time unit
][idx];
});
format('2024-06-20', 'my-lang');
```
### Response
#### Success Response
None
#### Response Example
None
```
--------------------------------
### Format ISO String
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/01-format.md
Formats an ISO 8601 date string into a relative time string.
```typescript
format('2018-12-12');
```
--------------------------------
### Default Import (CommonJS)
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Use this import method for CommonJS environments. Ensure your package.json's 'main' field points to 'dist/index.cjs'.
```typescript
const { format, render, cancel, register } = require('timeago.js');
```
--------------------------------
### format(date, locale, opts)
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md
Formats a given date into a human-readable relative time string. Supports various date input formats and locale customization.
```APIDOC
## format(date, locale, opts)
### Description
Formats a date into a relative time string (e.g., "2 hours ago"). Supports JavaScript Date objects, ISO strings, Unix timestamps, and relative dates with options.
### Parameters
#### Path Parameters
- **date** (Date | string | number) - Required - The date to format. Can be a Date object, ISO string, Unix timestamp (milliseconds), or a string representing a date.
- **locale** (string) - Optional - The locale to use for formatting (e.g., 'en_US', 'zh_CN'). Defaults to 'en'.
- **opts** (object) - Optional - An options object for advanced configuration.
### Options
- **relativeDate** (string | number | Date) - Use a specific date as the reference point instead of the current time.
### Input Formats
- JavaScript Date: `format(new Date('2024-06-20'))`
- ISO string: `format('2024-06-20')`, `format('2024-06-20T10:30:00')`
- Unix timestamp (milliseconds): `format(1718918400000)`
- Relative to specific date: `format('2024-06-20', 'en_US', { relativeDate: '2024-06-01' })`
### Example
```javascript
timeago.format('2024-06-20', 'en_US')
```
```
--------------------------------
### render()
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/00-index.md
Renders timeago relative strings for a collection of DOM elements. These elements will auto-update at specified intervals.
```APIDOC
## render()
### Description
Renders timeago relative strings for a collection of DOM elements. These elements will auto-update at specified intervals.
### Method
function
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **nodes** (NodeList | HTMLElement[]) - Required - A list of DOM nodes to render timeago strings in. Each node should have a `datetime` attribute.
- **locale** (string) - Optional - The locale to use for formatting. Defaults to 'en_US'.
- **opts** (Opts) - Optional - An options object for advanced configuration, such as `minInterval`.
### Request Example
```javascript
import { render } from 'timeago.js';
// HTML:
const nodes = document.querySelectorAll('.timestamp');
render(nodes, 'en_US', { minInterval: 5 });
```
### Response
#### Success Response
None (modifies DOM directly)
#### Response Example
None
```
--------------------------------
### TimerPool
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/05-types.md
Internal record of active timers used for real-time rendering updates.
```APIDOC
## TimerPool
Internal record of active timers for real-time rendering.
```typescript
type TimerPool = Record
```
Structure:
```typescript
{
123456789: 0, // timerId -> placeholder (always 0)
234567890: 0,
// ...
}
```
Each key is a unique timer ID (return value of `setTimeout`), with a static value of `0`.
### Behavior
- Timer IDs are stored as object keys for O(1) lookup
- Timers are cleared from the pool in the `cancel()` function
- The global `TIMER_POOL` is maintained internally in `src/realtime.ts`
- Not exposed to users; only referenced internally
```
--------------------------------
### Set Relative Date for Formatting
Source: https://github.com/hustcc/timeago.js/wiki/timeago.js-v1.x.x-usgae-documents
Set a specific date to be used as the reference point for relative time calculations instead of the current date. Then format a date string, optionally specifying a locale.
```js
var timeago = timeago('2016-06-10 12:12:12'); // set the relative date here.
timeago.format('2016-06-12', 'zh_CN');
```
--------------------------------
### Importing Specific Locales (CommonJS)
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/09-imports-exports.md
Import specific locale modules for CommonJS environments to enable tree-shaking.
```typescript
const ja = require('timeago.js/lib/ja');
const fr = require('timeago.js/lib/fr');
```
--------------------------------
### Add Custom Language Locale
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md
Use the `register` function to add support for custom languages or locales. Provide the locale string and a function that defines the language rules.
```javascript
register('my-lang', myFunction)
```
--------------------------------
### HTML Elements for Rendering
Source: https://github.com/hustcc/timeago.js/blob/master/_autodocs/11-quick-start.md
For the `render` function to work, HTML elements must include a `datetime` attribute containing the date information in a recognized format.
```html
```
--------------------------------
### Import timeago.js Functions
Source: https://github.com/hustcc/timeago.js/blob/master/README.md
Import necessary functions from the timeago.js library for use in your TypeScript or JavaScript project. Alternatively, include it via a script tag in HTML to access the global `timeago` variable.
```typescript
import { format, render, cancel, register } from 'timeago.js';
```
```html
```