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

Overview

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

Comments
  • How to handle differing server and client times

    How to handle differing server and client times

    What's the best way of handling when the server and client times differ? For example, if the clients clock is 5 mins behind, it would show 'in 5 minutes' instead of 'just now' which looks wrong.

    I tried to enter a relative date like timeago('2016-06-10 12:12:12'), but after doing so it seems that the real-time updating no longer works. I believe this is because the diffSec function uses that date as the base to compare against rather than new Date().

    // calculate the diff second between date to be formated an now date.
    function diffSec(date, nowDate) {
      nowDate = nowDate ? toDate(nowDate) : new Date();
      return (nowDate - toDate(date)) / 1000;
    }
    

    If this isn't possible currently, perhaps if a relative date is entered, it should instead store an offset against new Date() and use that when working out the difference?

    opened by jshah4517 22
  • Adjust

    Adjust "days"

    I noticed something. If I do timeago().format(new Date("2017-08-09 18:00")) (it is 2017-08-11 12:39 right now) I get 1 day ago. But in human terms, thats wrong. For me it was actually 2 days ago, even if it weren't 48 hours. If you say 1 day ago I assume that it was yesterday, not the day before late in the night.

    opened by Nemo64 20
  • Add datetime attribute alternative following W3C recommendations

    Add datetime attribute alternative following W3C recommendations

    Picky, I know. In your README.md you mentioned the possible use of a data-timeago attribute instead of the "W3C-illegal" datetime attribute (see W3C Recommendation) which we couldn't actually use before this PR. This PR adds the possibility to use the data-timeago attribute for the automatic rendering while maintaining backwards compatibility.

    opened by RoiEXLab 19
  • [discuss] v2.0.x version

    [discuss] v2.0.x version

    :walking: The v1.x.x received so many feedbacks and suggestions, so v2.0.x will do it.

    v2.0.x will not compatible with v1.0.x, details below:

    • [x] Read date from datetime attribute for <time datetime='xxxxx'>.
    • [x] API register will be a static method, replace of an instance method.
    • [x] Will use coding style of new timeago().

    What else, welcome to additional. ref #12 #23 #47 #59 #61

    help wanted question 
    opened by hustcc 17
  • Optimizations for using in components

    Optimizations for using in components

    When this library is used in components with life-cycles (e.g. react), capabilities of unregistering a single relative time instance is critical.

    Current implementations have several disadvantages in such circumstances:

    1. Does not support canceling timer for a singular DOM in a timeago instance. Instead all timers in the instance are cancelled. Because of this, we need to create a timeago instance for every single relative time instead of create one and share, which is really slow when there are many relative times to display (e.g. long lists).

    2. Does not share member functions across timeago instances so that every timeago instance needs more memory, which makes it even worse --> Please use prototypes to eliminate the memory cost.

    opened by breezewish 16
  • Add minimal interval to refresh (timeago.render)

    Add minimal interval to refresh (timeago.render)

    This PR adds the minimal interval option to refresh intto timeago.render.

    This option will help developers to avoid disturbing users especially in case of having multiple sub-minute elements. An example is available at https://cl.ly/2r39322u3e23 (adapted from gitlab-org/gitlab-ce#47976).

    Signed-off-by: Takuya Noguchi [email protected]

    opened by tnir 15
  • Generate a build with all locales included

    Generate a build with all locales included

    It would be useful to generate a minimised build with all locales included and registered, similar to what Moment.js does, e.g. timeago-with-locales.min.js, so that anyone wanting to include all locales can just load that - even if it is a larger file.

    opened by shaneog 13
  • Add ability to cancel render for specific node, update readme

    Add ability to cancel render for specific node, update readme

    #109 Attempt to add support for cancelling single timer for specific node

    minified size increased to 2.02 kb :disappointed: If someone has better ideas - lets discuss them together

    Also this PR fixes unpleasant issue with this code - there are a lot of "dead" timers that are stored in the array until they are explicity removed by calling cancel. By "dead" timers I mean timers that are already executed but their ids are still in the array. Potentially it causes memory leaks.

    opened by likerRr 12
  • Added Georgian locale (ka_GE)

    Added Georgian locale (ka_GE)

    Added translations for the Georgian language.

    Although not very well known, Georgian is a unique language spoken only by the citizens of Republic of Georgia (for thousands of years).

    I love your library, and since I had to create a Georgian locale for my use anyway, I thought I might as well create a PR.

    Not a lot of libraries have Georgian translations, so your library will stand out even more now!

    opened by Lukakva 8
  • v4.0.0 is working in progress

    v4.0.0 is working in progress

    Working code is on branch master.

    • rewrite with es6.
    • coverage test cases to 100% with jest.
    • refactoring code structure.
    • bundle with rollup & babel.

    What to be done?

    • [x] test coverage, src & locales
    • [x] code of locales translated to ES6
    • [x] new API design
    • [x] locale file format

    new API

    import { format, render, cancel, register } from 'timeago.js';
    
    // format date to string
    const str = format(date, locale);
    
    // real time render
    render(dom, locale);
    
    cancel(dom); // cancel the dom
    
    cancel(); // cancel all
    
    // new locale
    register('new_locale', localeFunc);
    

    Welcome to pr and discuss.

    PR need 
    opened by hustcc 8
  • Cutoff option

    Cutoff option

    Has the implementation of a cutoff option ever been considered? This would display the original date if time distance is older than the cutoff.

    This is implemented in the jQuery plugin: https://github.com/rmm5t/jquery-timeago

    Would you consider a pull request for this feature?

    opened by edhollinghurst 8
  • Croatian, Serbian locale

    Croatian, Serbian locale

    hr.ts

    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 [
        ['tek sada', 'upravo sada'],
        ['prije %s sekundi', 'za %s sekunde'],
        ['prije 1 minute', 'za 1 minutu'],
        ['prije %s minuta', 'za %s minuta'],
        ['prije 1 sata', 'za 1 sat'],
        ['prije %s sata', 'za %s sata'],
        ['prije 1 dan', 'za 1 dan'],
        ['prije %s dana', 'za %s dana'],
        ['prije 1 tjedan', 'za 1 tjedan'],
        ['prije %s tjedna', 'za %s tjedna'],
        ['prije 1 mjeseca', 'za 1 mjesec'],
        ['prije %s mjeseci', 'za %s mjeseca'],
        ['prije 1 godine', 'za 1 godinu'],
        ['prije %s godina', 'za %s godina']
      ][index];
    };
    

    rs.ts

    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 [
        ['nedavno', 'ovog momenta'],
        ['pre %s sekundi', 'za %s sekunde'],
        ['pre 1 minute', 'za 1 minutu'],
        ['pre %s minuta', 'za %s minuta'],
        ['pre 1 sata', 'za 1 sat'],
        ['pre %s sata', 'za %s sata'],
        ['pre 1 dan', 'za 1 dan'],
        ['pre %s dana', 'za %s dana'],
        ['pre 1 nedelje', 'za 1 nedelju'],
        ['pre %s nedelje', 'za %s nedelju'],
        ['pre 1 mesec', 'za 1 mesec'],
        ['pre %s mesea', 'za %s meseca'],
        ['pre 1 godinu', 'za 1 godinu'],
        ['pre %s godina', 'za %s godina']
      ][index];
    };
    
    opened by idc77 0
  • Fix sourceMap support on package

    Fix sourceMap support on package

    Fixes https://github.com/hustcc/timeago.js/issues/240

    This is something I have found when publishing my packages to NPM, the src directory is published to NPM which the .map files refer to. There might be some alternative way to embed sourceMap src or something, but this solution has worked for me! Thanks for this package

    opened by cmdcolin 0
  • Documentation for importing languages

    Documentation for importing languages

    I'm trying to render in Spanish, and am not sure how to configure timeago.

    import { register, format, render, cancel } from 'timeago.js';
    import {esLocal} from 'timeago.js/lib/lang/es';
    register('es', esLocal);
    
                        const nodes = document.querySelectorAll('.timeago');
                        // use render method to render nodes in real time
                        render(nodes, 'es');
    

    I imagine I'm not registering it correctly, but I can't find the documentation on how to do that. Thanks.

    opened by tacman 0
Releases(v4.0.2)
Owner
hustcc
@alipay 内推,参入可视化开源项目,请加个人微信:AnyPlot。
hustcc
Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Try live example at https://duetds.github.io/date-picker/

Duet Date Picker Duet Date Picker is an open source version of Duet Design System’s accessible date picker. Duet Date Picker can be implemented and us

Duet Design System 1.6k Jan 6, 2023
Create Persian Calendar as html helper with tag builder c# , and convert selected persian date to gregorian date

Persian-Calendar Use JS,Html,CSS,C# White theme for Persian Calendar , easy to use. Create Persian Calendar as html helper. Use Tag builder in c# for

Tareq Awwad 4 Feb 28, 2022
A date picker web component, and spiritual successor to duet date picker

<date-picker> A date picker web component, based on duet date picker, except authored with Lit and using shadow DOM. This is a work in progress. Todo:

Nick Williams 25 Aug 3, 2022
⏰ Day.js 2KB immutable date-time library alternative to Moment.js with the same modern API

English | 简体中文 | 日本語 | Português Brasileiro | 한국어 | Español (España) | Русский Fast 2kB alternative to Moment.js with the same modern API Day.js is a

null 41.7k Dec 28, 2022
🕑 js-joda is an immutable date and time library for JavaScript.

js-joda is an immutable date and time library for JavaScript. It provides a simple, domain-driven and clean API based on the ISO8601 calendar.

null 1.5k Dec 27, 2022
⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API

English | 简体中文 | 日本語 | Português Brasileiro | 한국어 | Español (España) | Русский Fast 2kB alternative to Moment.js with the same modern API Day.js is a

null 41.7k Dec 28, 2022
A tiny and fast zero-dependency date-picker built with vanilla Javascript and CSS.

A tiny zero-dependency and framework-agnostic date picker that is incredibly easy to use! Compatible with any web UI framework, vanilla JS projects, and even HTML-only projects!

Nezar 1 Jan 22, 2021
⏳ Modern JavaScript date utility library ⌛️

date-fns provides the most comprehensive, yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js. ?? Documentation

date-fns 30.6k Dec 29, 2022
CalendarPickerJS - A minimalistic and modern date-picker component/library 🗓️👨🏽‍💻 Written in Vanilla JS

CalendarPickerJS The simple and pretty way to let a user select a day! Supports all major browser. Entirely written in Vanilla JavaScript with no depe

Mathias Picker 15 Dec 6, 2022
This library provide a fast and easy way to work with date.

Calendar.js Calendar.js provide a fast way to work with dates when you don't wanna deal with hours, minute, second and so on. It means that Calendar.j

ActuallyNotaDev 3 Apr 27, 2022
A project implementing a datepicker with format dd/MM/yyyy from scratch.

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

José Antônio 2 Jan 11, 2022
Reusable date picker component for React

React DayPicker DayPicker is a reusable date picker component for React. $ npm install react-day-picker@next Beta version ⚠️ This branch is for the ne

Giampaolo Bellavite 4.8k Dec 28, 2022
DEPRECATED: Timezone-enabled JavaScript Date object. Uses Olson zoneinfo files for timezone data.

TimezoneJS.Date A timezone-enabled, drop-in replacement for the stock JavaScript Date. The timezoneJS.Date object is API-compatible with JS Date, with

Matthew Eernisse 830 Nov 20, 2022
Date() for humans

date Date is an english language date parser for node.js and the browser. For examples and demos, see: http://matthewmueller.github.io/date/ Update: d

Matthew Mueller 1.5k Jan 4, 2023
Lightweight and simple JS date formatting and parsing

fecha Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js. NPM npm install fecha --save

Taylor Hakes 2k Jan 5, 2023
A lightweight, locale aware formatter for strings containing unicode date tokens.

Date Token Format A lightweight (~2kB), locale aware formatter for strings containing unicode date tokens. Usage Install the package using: yarn add d

Donovan Hutchinson 1 Dec 24, 2021
Nepali Date Picker jQuery Plugin 🇳🇵

Nepali Date Picker Nepali Date Picker jQuery Plugin for everyone. ???? Installation npm install nepali-date-picker Demo and Documentation https://leap

Leapfrog Technology 70 Sep 29, 2022
React Native Week Month Date Picker

React Native Week Month Date Picker Date picker with a week and month view Installation npm install react-native-week-month-date-picker Dependencies T

Noona 119 Dec 27, 2022
Easy to get a date.

date2data 테이블에 날짜별 데이터 넣을 때마다 새로 객체 만들어서 작업하기가 매우 귀찮아서 만들었다. moment.js를 쓰기에는 구현하고자 하는 내용이 너무 가벼웠음 Install npm i date2data Usage import {getMonthlyDate

Duho Kim 3 Apr 12, 2022