timeago.js is a nano library(less than
2 kb
) used to format datetime with*** time ago
statement. eg: '3 hours ago'.
ago
and time in
supported.Official website. React version here: timeago-react. Python version here: timeago.
Such as
Usagejust 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
import { format, render, cancel, register } from 'timeago.js';
or import with script
tag in html file and access global variable timeago
.
<script src="dist/timeago.min.js"></script>
APIformat('2016-06-12', 'en_US');
There only 4 API below.
format(date[, locale = 'en_US', opts])
, format a Date instance / timestamp / date string to string.
import { format } from 'timeago.js';
Â
format(1544666010224);
Â
format(new Date(1544666010224));
Â
format('2018-12-12');
Â
format(1544666010224, 'zh_CN');
Â
format(1544666010224, 'zh_CN', { relativeDate: '2018-11-11' });
Â
format(Date.now()Â -Â 11Â *Â 1000Â *Â 60Â *Â 60);Â
The default locale is en_US
, and the library contains en_US
and zh_CN
build-in.
render(dom[, locale = 'en_US', opts])
cancel([dom])
Make a dom with
datetime
attribute automatic rendering and cancel.
HTML code:
<div class="timeago" datetime="2016-06-30 09:20:00"></div>
Javascript code:
import { render, cancel } from 'timeago.js';
Â
const nodes = document.querySelectorAll('.timeago');
Â
render(nodes, 'zh_CN');
Â
Â
cancel();
Â
cancel(nodes[0])
The 3rd parameter opts
contains:
export type Opts = {
 Â
  readonly relativeDate?: TDate;
 Â
  readonly minInterval?: number;
};
The DOM object should have the attribute
datetime
with date formatted string.
register(locale, localeFunc)
, register a new locale, build-in locale contains:en_US
,zh_CN
, all locales here.
You can register your own language with register
API.
Contributionsconst 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('my-locale', localeFunc);
Â
format('2016-06-12', 'my-locale');
npm test
. How to write test cases, see locales test cases.MIT@hustcc
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4