Giter VIP home page Giter VIP logo

timeago.js's Introduction

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

timeago.js's People

Contributors

ajphukan avatar alaatm avatar alanwei0 avatar alex-werner avatar breakfastcerealkillr avatar finwo avatar gautamkrishnar avatar gowza avatar greg-dev avatar hustcc avatar ivantedja avatar lauhakari avatar likerrr avatar niklasf avatar nucreativa avatar olehreznichenko avatar orkon avatar ramkrishnatkr avatar renatoassis01 avatar riley-stroud-ck avatar roiexlab avatar samuelmeuli avatar sethmichaellarson avatar shaneog avatar shevchenkonik avatar sky93 avatar sufuf3 avatar tnir avatar tomision avatar tomonari-t avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

timeago.js's Issues

[discuss] v2.0.x version

🚶 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:

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

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

Allow using attributes other than data-timeago

For example, when timeago.js is applied on <time> tags, it can make use of the datetime attribute. Currently we need to duplicate datatime attribute to data-timeago attribute, which is nonsense.

defaultLocale not exists, will error.

const newTimeAgoDefaultLocale = timeago('2016-03-01 12:00:00', 'pl');
t.equal(newTimeAgoDefaultLocale.format('2016-02-28 12:00:00'), '2 days ago');

Will except.

Can it reverse analyze ?

Hi:
Can timeago analyze string to datetime ? like this:
input: 1 year ago
output: a date value ( 2016-11-09)

😃 😃 😃

ES6

My build gives the following error:

'default' is not exported by node_modules/timeago.js/dist/timeago.min.js

I use the suggested import:

import timeago from 'timeago.js'

Certain timestamps cause busy loops when automatically rendered

When certain timestamps are rendered by timeago's render() function, the delta between the timestamp and the current time that it calculates in diffSec() and passes to nextInterval() results in a timeout value larger than the effective upper limit for major browsers' setTimeout() implementation according to the MDN docs. This results in the browser firing the timeout immediately instead of after the intended delay and, since the function called after the timeout (doRender()) registers another timeout with itself as the callback, creates a busy loop in the browser.

As an example, see the value nextInterval() returns for the two dates below (roughly a month apart):

> diffSec("2016-12-01T12:00:12Z", "2017-01-05T12:00:00Z")
3023988
> nextInterval(3023988)
2232013
> nextInterval(3023988) * 1000
2232013000

That 2232013000 value gets passed to setTimeout(), and the docs linked above describe what happens in such a situation:

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

Limiting this value with Math.min() to anything less than or equal to 2147483647 fixes this:

  }, Math.min(nextInterval(diff) * 1000, 0x7FFFFFFF));

Plunker link with an example (using a copy-pasted and modified version of timeago): https://plnkr.co/edit/2nlfb8eWusa3yS1zuW47

(Originally found via https://gitlab.com/gitlab-org/gitlab-ce/issues/25132)

中文 一周后

中文一周后,应该为1周后,和其他保持一致。

Incorrect plural forms in pl locale

The current Polish translation needs some corrections, for example it shows "11 sekundy temu", ..., "19 sekundy temu" instead of "11 sekund temu", ..., "19 sekund temu". There are similar problems with other units of time, you can see it when running tests I've added in a separate PR #99

11 days instead of 1 week

Is it possible to use 11 days instead of 1 week for example?

timeago.register('custom', function(number, index) {
    // index = 8
    // number = 1
});

Issue with 11..19 and n1 numbers and polish locale

I've created Polish locale (will create PR) but have problems. In polish
"1 month" ago is "1 miesiąc temu"
"%s months ago" is "%s miesięce temu"
but for numbers 11..19, 21 31, ..., 91 is "%s miesięcy temu"

and there is no way to have this locale without modification of the library. Maybe locale be a function that accept number and unit like:

function locale(number, unit) {
   var str = number.toString();
   if (unit == 'hours') {
       if (number == 1) {
          return ['1 godzinę temu', 'za 1 godzinę'];
       } else if (str.length == 2 && str[0] == "1" || number % 10 == 1) {
          return ['%s godzin temu', 'za %s godzin'];
      } else {
        return ['%s godziny temu', 'za %s godziny'];
      }
  }
}

and the code can detect if locale is function or array.

Taking too much CPU with jQuery

Found something very weird on Firefox 45.6.0 on Debian. Adding a few instance.render() with jQuery uses lots of CPU, although on Chromium things were reasonable.

I was able to bring down CPU usage using the following loop:

var timeagoInstance = new timeago()
var $timeago = $('.timeago')
var r
// timeagoInstance.render($timeago, 'fr')
for (r = 0; r < $timeago.length; ++r) {
  timeagoInstance.render($timeago[r], 'fr')
}

If instead of a for loop I use

timeagoInstance.render($timeago, 'fr')

Then CPU usage seems to explode.

Generate separate timeago.js with only english locale

It would be nice to have a generated timeago.js that only included the english as it's default locale. I am currently in a situation where I will not be using the chinese locale and would like to have them removed so that I can optimize the size of my third party dependencies.

Imo, it would be easier to have this part of this repo rather than me having to maintain my own fork.

Something like dist/timeago.en.js with only english as the default locale would be perfect!

Webpack vs Gulp

I had a question as to why we are using gulp and webpack. Why not just use one or the other?

locale translations are needed

The locales is here, you can add the miss name.

  1. Please sort by dictionary.
  2. Please ensure the accuracy.
  3. Please keep file size tiny.

How to ?

  1. Add you locale file into locales dir.
  2. Add you locale key into file.
  3. Add testcases into tests/lang dir.
  4. Then run npm test, if all passed, then commit the pr.

  • ar
  • az
  • az
  • be
  • bg
  • bs
  • ca
  • cs
  • cy
  • da
  • de
  • dv
  • el
  • en
  • en_short
  • es
  • et
  • eu
  • fa
  • fi
  • fr
  • gl
  • he
  • hr
  • hu
  • hy
  • id
  • in_BG
  • in_HI
  • in_ID
  • is
  • it
  • ja
  • jv
  • ko
  • ky
  • lt
  • lv
  • mk
  • ml
  • my
  • nb_NO
  • nl
  • nn_NO
  • no
  • pl
  • pt_BR
  • pt
  • ro
  • rs
  • ru
  • rw
  • si
  • sk
  • sl
  • sr
  • sv
  • ta
  • th
  • tr
  • uk
  • uz
  • vi
  • zh_CN
  • zh_TW

Thanks ^_^

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?

When diff is Decimal & Negative

When diff is Decimal & Negative, the real-time render is not REAL.

e.g.

when diff = -18.12, it will be rendered per 2 seconds, must be 1 second.

Please Release New Version

Hi,

if you can, Please Release new version, because in current version, Persian Locale is not aviable for use.

Thanks to anyway.

Ignore "n seconds ago" and use "just now"

Is there any way to configure the library to not show "12 seconds ago" but instead use "just now" for values up to 59 seconds? I find that showing the seconds tends to distract the user because it is constantly updated.

I could register my own locale with the same value for seconds and minutes, but that seems hacky and does not translate for other locales.

can't render some timedata correctly

<span class="timeago" datetime="Tue Jan 31 2017 00:47:58 GMT+0300 (Turkey Standard Time)" data-popup="tooltip" data-placement="bottom" data-original-title="31 Ocak 2017 00:47">2 days ago</span> => renders "2 days ago"

<span class="timeago" datetime="Sat Jan 28 2017 01:06:12 GMT+0300 (Turkey Standard Time)" data-popup="tooltip" data-placement="bottom" data-original-title="28 Ocak 2017 01:06">just now</span> =>renders "just now"

Usage in Chrome Extension

Can you advise me how to use this in a chrome extension?
I have included minified file in HTML but can't use npm to install.

疑问

src/timeago.js

  1. 第44行的if判断是否可以去掉?
  2. 第146行 0x7FFFFFFF 选这个数的标准是?转换成天数约为24.86天,不太明白!

TypeScript errors with noImplicitAny: true

Hello. I'm having these errors when using noImplicitAny: true in tsconfig.json. Basicly it needs return type to defined, just not sure which one and how to do it. Is timeago.d.ts file created automatically?

ERROR in [at-loader] ./node_modules/timeago.js/timeago.d.ts:4:5 
    TS7013: Construct signature, which lacks return-type annotation, implicitly has an 'any' return type.

ERROR in [at-loader] ./node_modules/timeago.js/timeago.d.ts:5:5 
    TS7013: Construct signature, which lacks return-type annotation, implicitly has an 'any' return type.

all dates showing just now

applying timago.js with jquery selector render date to just now,

timeago().render($('.lastConnected'));

gives just now on every time and doesn't update

Tests failing with expected 5月后 and actual 4月后

Some tests are failing with what looks like off by one errors, for example:

Locale testcase for [zh_CN]
[...]
ok 1312 should be equal
ok 1313 should be equal
ok 1314 should be equal
not ok 1315 should be equal
  ---
    operator: equal
    expected: '5月后'
    actual:   '4月后'
    at: module.exports (/home/niklas/Projekte/timeago.js/tests/locales/zh_CN.js:52:5)
    stack: |-
      Error: should be equal
          at Test.assert [as _assert] (/home/niklas/Projekte/timeago.js/node_modules/tape/lib/test.js:212:54)
          at Test.bound [as _assert] (/home/niklas/Projekte/timeago.js/node_modules/tape/lib/test.js:64:32)
          at Test.equal.Test.equals.Test.isEqual.Test.is.Test.strictEqual.Test.strictEquals (/home/niklas/Projekte/timeago.js/node_modules/tape/lib/test.js:347:10)
          at Test.bound [as equal] (/home/niklas/Projekte/timeago.js/node_modules/tape/lib/test.js:64:32)
          at module.exports (/home/niklas/Projekte/timeago.js/tests/locales/zh_CN.js:52:5)
          at files.forEach.file (/home/niklas/Projekte/timeago.js/tests/test.js:18:37)
          at Array.forEach (<anonymous>)
          at fs.readdir (/home/niklas/Projekte/timeago.js/tests/test.js:13:11)
          at FSReqWrap.oncomplete (fs.js:149:15)
  ...
ok 1316 should be equal
ok 1317 should be equal
ok 1318 should be equal
[...]

Seems to be always in the

t.equal(tb.addMonths(5), '....');

test case.

how to use with webpack?

const timeago = require('timeago.js/dist/timeago.min.js');
require('timeago.js/dist/timeago.locales.min.js');

the second line gives;

Uncaught ReferenceError: timeago is not defined
    at Object.s.exports (timeago.locales.min.js:1)
    at n (timeago.locales.min.js:1)
    at timeago.locales.min.js:1
    at Object.<anonymous> (timeago.locales.min.js:1)
    at __webpack_require__ (bootstrap a76c704…:19)
    at Object.<anonymous> (components.js:26)
    at Object.defineProperty.value (components.js:66)
    at __webpack_require__ (bootstrap a76c704…:19)
    at Object.defineProperty.value (common.js:13)
    at __webpack_require__ (bootstrap a76c704…:19)

any ideas?

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?

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.

Add version number to built files

It would be nice to have the version number in the generated files (in /dist)

Before:

/**
 * Copyright (c) 2016 hustcc
 * License: MIT
 * https://github.com/hustcc/timeago.js
**/

After:

/**
 * Copyright (c) 2016 hustcc
 * License: MIT
 * Version: 2.0.2
 * https://github.com/hustcc/timeago.js
**/

Defining a timezone

I can't seem to find documentation that states that this exists. But I have a problem right now, where my server records in UTC, but the client could be an different timezone, and it will compare the timestamp from UTC to their current. Which causes problems with timestamps appearing as "in 3 hours" when in reality they were 23 minutes ago. I know I can compare the client time to UTC and subtract the difference. But I would like to avoid that if there is a built in solution I'm just not aware of?

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.

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.

Error using library with TypeScript 2.2.2

When using the code snippet:

new timeago().format(somedate)

I get a Typecript error:

Only a void function can be called with the 'new' keyword.

I'm using timeago.js v3.0.1, here is a screenshot of my usage.

screen shot 2017-05-04 at 11 22 10

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.