• Stars
    star
    5,033
  • Rank 7,863 (Top 0.2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🕗 ⌛ timeago.js is a tiny(2.0 kb) library used to format date with `*** time ago` statement.

timeago.js

timeago.js is a nano library(less than 2 kb) used to format datetime with *** time ago statement. eg: '3 hours ago'.

  • i18n supported.
  • Time ago and time in supported.
  • Real-time render supported.
  • Node and browser supported.
  • Well tested.

Official website. React version here: timeago-react. Python version here: timeago.

npm Version unpkg Build Status Coverage Status Dist gzip npm Download npm License

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

Usage

  • install
npm install timeago.js
  • import
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>
  • example
// format the time with locale
format('2016-06-12', 'en_US');

CDN

Alternatively to NPM, you can also use a CDN which will reflect the latest version as soon as it is published to npm.

<script src="//unpkg.com/timeago.js"></script>

API

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.

  • render & cancel

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');

// 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])

The 3rd parameter opts contains:

export type Opts = {
  /** the relative date */
  readonly relativeDate?: TDate;
  /** the realtime min update interval */
  readonly minInterval?: number;
};

The DOM object should have the attribute datetime with date formatted string.

  • 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');

Contributions

  1. The website is based on rmm5t/jquery-timeago which is a nice and featured project but it depends on jQuery.
  2. locale translations: The library needs more locale translations. You can:
  • Open an issue to write the locale translations, or submit a pull request. How to ? see locales translation.
  • Please test the locale by exec npm test. How to write test cases, see locales test cases.

LICENSE

MIT@hustcc

More Repositories

1

JS-Sorting-Algorithm

一本关于排序算法的 GitBook 在线书籍 《十大经典排序算法》,多语言实现。
Java
5,082
star
2

echarts-for-react

⛳️ Apache ECharts components for React wrapper. 一个简单的 Apache echarts 的 React 封装。
TypeScript
4,321
star
3

canvas-nest.js

♋ Interactive Particle / Nest System With JavaScript and Canvas, no jQuery.
JavaScript
4,253
star
4

PyG2Plot

🎨 Python3 binding for `@AntV/G2Plot` Plotting Library .
Python
1,012
star
5

PTHospital.chrome

⚠️ 🏥 Chrome浏览器插件——打开莆田系医院网站,发出警告提醒、显示医院信息。
JavaScript
573
star
6

onfire.js

🔫 onfire.js is a nano version (~500b) for event-emitter.
TypeScript
498
star
7

timeago-react

🕗 Simple and efficient react component to format date with `*** time ago` statement. eg: '3 hours ago'.
TypeScript
416
star
8

xmorse

🌞 ~1.5Kb morse code library for all. 一个支持 Unicode 中文摩斯密码编码的 Javascript 库。
TypeScript
312
star
9

jest-canvas-mock

🌗 A module used to mock canvas in Jest.
JavaScript
300
star
10

gantt-for-react

🌿 Frappe Gantt components for React wrapper. 一个简单的甘特图 React 组件封装。
JavaScript
291
star
11

react-adsense

📽️ a simple React-component for Google AdSense / Baidu advertisement.
JavaScript
263
star
12

jest-date-mock

🌗 Mock `Date` when run unit test cases with jest. Make tests of Date easier.
JavaScript
259
star
13

timeago

⌛ Simple library used to format datetime with `*** time ago` statement. eg: "3 hours ago".
Python
221
star
14

ribbon.js

🎀 Only 1kb javascript gist to generate a ribbon in your website with HTML5 canvas.
JavaScript
219
star
15

webhookit

:octocat: Simple git webhook cli tool for automation tasks, bind git webhook to action.
Python
192
star
16

alimask

😷 alimask 是一个使用 canvas 生成类似阿里巴巴内部网站水印图片的 JavaScript 库。
JavaScript
176
star
17

size-sensor

🌿 1Kb DOM element size sensor which will callback when size changed.
JavaScript
166
star
18

placeholder.js

⚡ < 1Kb library to generate image placeholders on client side
PHP
161
star
19

jest-electron

❯ ⚛️The easiest way to run and debug test cases in electron with jest.
TypeScript
144
star
20

chrome-qrcode

⚡ A Chrome plugin to Genrate QRCode of URL / Text, or Decode the QRcode in website. 一个Chrome浏览器插件,用于生成当前URL或者选中内容的二维码,同时可以用于解析网页上的二维码内容。
JavaScript
133
star
21

iReact

🎁 iReact: Fantastic React Components and Libraries! Makes it easy for you to pick one that’ll work for you.
JavaScript
82
star
22

mac.py

⚡A python lib to search Manufacturer of physical network card by mac address. 一个通过物理地址查询网卡所属厂商的Python库。
Python
68
star
23

pixi-action

🏇 pixi-action is a plugin for Pixi.js to create actions and animations easily, inspired by Cocos2d-x.
HTML
65
star
24

word-table

◼️ a simple javascript (browserjs / nodejs) library for drawing tables in the terminal / console, unicode supported.
JavaScript
60
star
25

wrapcache

⚡ A python Function / Method OUTPUT cache system base on function Decorators.
Python
58
star
26

simple-shields

🔰 a simple Shields Badge service with PHP & SVG, Simple, Fast, Stable and Easy Deploy.
HTML
50
star
27

GitHub-Helper.Chrome

:octocat: A Chrome plugin for GitHub Helper. Get a better idea about GitHub.
CSS
40
star
28

GitHub-Repo-Widget.js

:octocat: A good looking github repository widget to add to your website. Not depends on jQuery or Other.
JavaScript
39
star
29

aliyun-oss-deploy

🙈 一个 nodejs 命令行工具,用于部署静态资源到 aliyun oss,支持代码方式和 CLI 方式!
JavaScript
35
star
30

slice.js

🌌 nano library to enhance String.substring / Array.slice with python slice style by Proxy.
JavaScript
34
star
31

hint

重构到 ---> https://github.com/hustcc/lint-md
Python
34
star
32

G2Plot-QRCode

Draw a QRCode with G2Plot.
TypeScript
33
star
33

tplv

👣 Nano string template library for modern, based on ES6 template string syntax.
TypeScript
33
star
34

post-messenger

👶 ~1 Kb wrapper of window.postMessage for cross-document communication.
JavaScript
28
star
35

filesize.js

🔥 filesize.js is a simple(~360 b) module to make file size human-readable.
TypeScript
26
star
36

variable-type

👏 ~ 1 kb. Schema validation. 一个只有 1 kb 的用于变量结构校验的库。
TypeScript
24
star
37

hrn

🔢 Type module to format number into Human-Readable-String. e.g. 4567 -> 4.6 k.
JavaScript
23
star
38

miz

🎯 Generate fake data, Just like a person.
TypeScript
22
star
39

React-G2Plot

🤖 Unofficial react component wrapper for @antvis/G2Plot
TypeScript
21
star
40

return-top

Pure javascript achieve click image to return top of website with animation
JavaScript
19
star
41

xhr.js

🌎 xhr.js is a library(< 2Kb) to make AJAX/HTTP requests with XMLHttpRequest.
JavaScript
19
star
42

jchatting

Chat system developed by Java Swing & Java Socket. 使用Java Swing和Java Socket API实现的聊天系统。
Java
18
star
43

warpart

使用 Flask 做的一个唐诗展示网站。
Python
18
star
44

G2-50-Questions

❓ 500 Questions about G2.
15
star
45

diff-text

Just get the diff of a simple inline text, simple mode.
JavaScript
14
star
46

PrimeTable

Primes Table which Less then Ten million (10000000) 一千万以内的素数表(质数表)。
JavaScript
13
star
47

ding-robot

🤖 钉钉机器人 SDK for Node.js。
JavaScript
13
star
48

babel-plugin-optimize-i18n

🔑 优化国际化文案的 Babel 插件,可以减少国际化文案 40% ~ 50% 的 bundle size。
JavaScript
13
star
49

bmt

📏 in Browser, Measure Text width.
TypeScript
12
star
50

limit-size

🌤️ Lightweight, Convenient, Fast command tool to control your file size by CI, size-limit is too bloated.
TypeScript
11
star
51

yuque-lint

Markdown style lint service for Yuque.com base on webhook.
JavaScript
11
star
52

uri-parse

🔗 Mini data-uri parser for nodejs and browser. No dependencies!
JavaScript
11
star
53

KeyHelper

😭 好怀念^_^ 基于 Java Swing 的一款键盘改键程序,初衷是用于 Dota 物品和英雄技能改键。
Java
11
star
54

horse.js

🐴 < 3Kb. autocomplete component of pure javascript. 纯Javascript实现的轻量简洁的提示组件。
JavaScript
11
star
55

g2-for-react

📈g2 在 React 上的简单组件包装。React component wrapper of @antvis g2.
JavaScript
11
star
56

clz

✍️ Serverless & Beautiful third-part comment system base on lean cloud.
TypeScript
11
star
57

page-fps

🖼️ Inject fps indicator into your page for web performance.
TypeScript
8
star
58

byte-parser

8️⃣ (130B) Parse byte string to byte number, e.g. 1.2 Kb -> 1228.8, Kb, Mb, Gb, Tb, Pb, Eb, Zb, Yb supported.
TypeScript
7
star
59

immutability-util

🌿 Mutate a copy of data without changing the original source by path string, just like the get/set in lodash. Inspired by immutability-helper and rewrite with ES6.
JavaScript
7
star
60

npm-robbery

🚩 A command tool to register npm package name conveniently.
JavaScript
6
star
61

radix.js

💯 a simple javascript module to convent number to your radix, decimal supported.
JavaScript
6
star
62

evenly

💦 How to divide the gold evenly? No surplus. 怎么均匀并且无遗漏的分配黄金?
JavaScript
6
star
63

TODO

📝 A simple github authorized application for server multi-user TODO list.
JavaScript
6
star
64

react-testing-demo

🏁 Ensure code quality of React components with jest, enzyme, jsdom, eslint.
JavaScript
5
star
65

jest-less-loader

⚛️ Jest transformer for .less file.
TypeScript
5
star
66

anyplot

🟪 Web Components for Visualization based on G2.
TypeScript
5
star
67

babel-plugin-version

🏷️ babel plugin replace define identifier `__VERSION__` to pkg.version!
JavaScript
5
star
68

rc-size-sensor

React component wrapper for DOM element size sensor.
TypeScript
4
star
69

charts-perf

Performance tests for charts library.
TypeScript
4
star
70

short-unique-string

🆎 Generate short unique id string locally, used optimize javascript code.
JavaScript
3
star
71

hustcc.github.io

Code for my GitHub profile.
HTML
3
star
72

what.js

👻 only 0.25 kb. what.js is a simple library to get the type of variables. enganced typeof function.
JavaScript
3
star
73

chart-entanglement

模仿量子特效纠缠实现图表之间的联动。
JavaScript
3
star
74

jest-url-loader

⚛️ Similar with webpack's url-loader for Jest.
TypeScript
3
star
75

browser-support-badge

Generate browser version compatibility badges
JavaScript
3
star
76

emoticon.js

{︶。︶}┛ simple javascript library to generate random text emoticon.
JavaScript
3
star
77

hustcc

2
star
78

the-git-commit

:octocat: Nano nodejs module to get information of any git commit.
JavaScript
2
star
79

inject-version

Inject version into your source code when prepublishOnly.
TypeScript
2
star
80

string-shorten

Shorten a string with crc32 and radix.
JavaScript
2
star
81

jest-expect

🃏😂 Make jest expect more convenient.
JavaScript
2
star
82

gallery

Donate page.
CSS
1
star
83

template

Repository template for @hustcc
JavaScript
1
star
84

pypi-demo

Just a simple pypi package code structure. You can use it to register pypi package name.
Python
1
star