timeago.js is a nano library(less than 2 kb) used to format datetime with *** time ago statement. eg: '3 hours ago'.
Such as
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
- install
ohpm install @ohmos/timeago
- import
import { format, render, cancel, register } from '@ohmos/timeago';
- example
// format the time with locale
format('2016-06-12', 'en_US');
There only 4 API below.
- format
format(date[, locale = 'en_US', opts])
, format a Date instance / timestamp / date string to string.
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' });
// e.g.
format(Date.now() - 11 * 1000 * 60 * 60); // returns '11 hours ago'
The default locale is en_US
, and the library contains en_US
and zh_CN
build-in.
- register
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.
const localeFunc = (number: number, index: number, totalSec: number): [string, string] => {
// number: the timeago / timein number;
// index: the index of array below;
// totalSec: total seconds between date to be formatted and today's date;
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');