Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
javascript-time-ago
Advanced tools
The `javascript-time-ago` npm package is used to format dates and times in a human-readable way, such as '5 minutes ago' or '2 days ago'. It supports multiple languages and locales, making it a versatile tool for internationalization.
Basic Usage
This feature allows you to format a date into a human-readable string indicating the time elapsed since that date. The example shows how to set up the package for English and format a date to '1 minute ago'.
const TimeAgo = require('javascript-time-ago');
const en = require('javascript-time-ago/locale/en');
TimeAgo.addLocale(en);
const timeAgo = new TimeAgo('en-US');
console.log(timeAgo.format(new Date(Date.now() - 60 * 1000))); // '1 minute ago'
Custom Styles
This feature allows you to define custom styles for formatting the elapsed time. The example demonstrates how to create a custom style and use it to format a date.
const TimeAgo = require('javascript-time-ago');
const en = require('javascript-time-ago/locale/en');
TimeAgo.addLocale(en);
const timeAgo = new TimeAgo('en-US');
const customStyle = {
steps: [
{ formatAs: 'second' },
{ formatAs: 'minute' },
{ formatAs: 'hour' },
{ formatAs: 'day' },
{ formatAs: 'week' },
{ formatAs: 'month' },
{ formatAs: 'year' }
]
};
console.log(timeAgo.format(new Date(Date.now() - 60 * 1000), customStyle)); // '1 minute ago'
Localization
This feature supports multiple languages and locales, allowing you to format dates in different languages. The example shows how to set up the package for both English and Spanish.
const TimeAgo = require('javascript-time-ago');
const en = require('javascript-time-ago/locale/en');
const es = require('javascript-time-ago/locale/es');
TimeAgo.addLocale(en);
TimeAgo.addLocale(es);
const timeAgoEn = new TimeAgo('en-US');
const timeAgoEs = new TimeAgo('es-ES');
console.log(timeAgoEn.format(new Date(Date.now() - 60 * 1000))); // '1 minute ago'
console.log(timeAgoEs.format(new Date(Date.now() - 60 * 1000))); // 'hace 1 minuto'
Moment.js is a widely-used library for parsing, validating, manipulating, and formatting dates. It offers extensive functionality for date and time manipulation, but it is larger in size compared to `javascript-time-ago` and has been deprecated in favor of more modern solutions.
date-fns provides a comprehensive set of functions for working with dates in JavaScript. It is modular, allowing you to import only the functions you need, which can result in smaller bundle sizes. It also supports internationalization, similar to `javascript-time-ago`.
timeago.js is a small library used to format dates in a 'time ago' style. It is lightweight and easy to use, but it may not offer as many customization options or support for as many locales as `javascript-time-ago`.
International higly customizable relative date/time formatter (both for past and future dates).
Formats a date to something like:
npm install javascript-time-ago --save
First, the library must be initialized with a set of desired locales.
// Time ago formatter.
import TimeAgo from 'javascript-time-ago'
// Load locale-specific relative date/time formatting rules.
import en from 'javascript-time-ago/locale/en'
import ru from 'javascript-time-ago/locale/ru'
// Add locale-specific relative date/time formatting rules.
TimeAgo.locale(en)
TimeAgo.locale(ru)
After the initialization step is complete it is ready to format relative dates.
import TimeAgo from 'javascript-time-ago'
const timeAgo = new TimeAgo('en-US')
timeAgo.format(new Date())
// "just now"
timeAgo.format(new Date(Date.now() - 60 * 1000))
// "a minute ago"
timeAgo.format(new Date(Date.now() - 2 * 60 * 60 * 1000))
// "2 hours ago"
timeAgo.format(new Date(Date.now() - 24 * 60 * 60 * 1000))
// "a day ago"
import TimeAgo from 'javascript-time-ago'
// cyka blyat idi nahui
const timeAgo = new TimeAgo('ru-RU')
timeAgo.format(new Date())
// "только что"
timeAgo.format(new Date(Date.now() - 60 * 1000)))
// "минуту назад"
timeAgo.format(new Date(Date.now() - 2 * 60 * 60 * 1000)))
// "2 часа назад"
timeAgo.format(new Date(Date.now() - 24 * 60 * 60 * 1000))
// "днём ранее"
Mimics Twitter style of time ago ("1m", "2h", "Mar 3", "Apr 4, 2012")
…
const timeAgo = new TimeAgo('en-US')
timeAgo.format(new Date(), 'twitter')
// ""
timeAgo.format(new Date(Date.now() - 60 * 1000), 'twitter')
// "1m"
timeAgo.format(new Date(Date.now() - 2 * 60 * 60 * 1000), 'twitter')
// "2h"
The built-in Twitter style uses Intl
internally for formatting day/month/year
labels. This is not an issue for modern web browsers but requies Intl
polyfill for a couple of older browsers and for Node.js (if you're running this code on server side). See the Intl
section of this document for Intl
polyfill instructions. When Intl
is not available Twitter style falls back to the default one.
timeAgo.format(new Date(), 'fuzzy')
Similar to the default style but with "ago" omitted:
No locale data is loaded by default: a developer must manually choose which locales must be loaded. This is to reduce the resulting javascript bundle size.
If the resulting bundle size is of no concern (e.g. a big enterprise application), or if the code is being run on server side, then use this helper to load all available locales:
require('javascript-time-ago/load-all-locales')
The above sections explained all the basics required for using this library in a project.
This part of the documentation contains some advanced topics for those willing to have a better understanding of how this library works internally.
Localization can be further customized by selecting one of the "flavours": long
, short
, or mabe some others (like tiny
defined for en
). Refer to locale/en
for an example.
import english from 'javascript-time-ago/locale/en'
english.tiny // '1s', '2m', '3h', '4d', …
english.short // '1 sec. ago', '2 min. ago', …
english.long // '1 second ago', '2 minutes ago', …
One can pass style
(string
or object
) as a second parameter to the .format(date, style)
function. The style
object can specify (all are optional):
flavour
– preferred labels variant (e.g. short
, long
)units
– a list of time interval measurement units which can be used in the formatted output (e.g. ['second', 'minute', 'hour']
)gradation
– custom time interval measurement units scaleoverride
– is a function of { elapsed, time, date, now }
. If the override
function returns a value, then the .format()
call will return that value. Otherwise the date/time is formatter as usual.(see twitter
style for an example)
A gradation
is a list of time interval measurement steps. A simple example:
[
{
unit: 'second',
},
{
unit: 'minute',
factor: 60,
threshold: 59.5
},
{
unit: 'hour',
factor: 60 * 60,
threshold: 59.5 * 60
},
…
]
factor
is a divider for the supplied time interval (in seconds)threshold
is a minimum time interval value (in seconds) required for this gradation stepthreshold
customization is possible, see ./source/gradation.js
for more info)granularity
can also be specified (for example, 5
for minute
to allow only 5-minute intervals)For more gradation examples see source/gradation.js
Built-in gradations:
import { gradation } from 'javascript-time-ago'
gradation.canonical() // '1 second ago', '2 minutes ago', …
gradation.convenient() // 'just now', '5 minutes ago', …
The localization resides in the locale
folder.
The format a localization is:
{
…
"day":
{
"past":
{
"one": "{0} day ago",
"other": "{0} days ago"
},
"future":
{
"one": "in {0} day",
"other": "in {0} days"
}
},
…
}
The past
and future
can be defined by any of: zero
, one
, two
, few
, many
and other
. For more info on which is which read the official Unicode CLDR documentation. Unicode CLDR (Common Locale Data Repository) is an industry standard and is basically a collection of formatting rules for all locales (date, time, currency, measurement units, numbers, etc).
To determine whether a certain amount of time (number) is one
, few
, or something else, javascript-time-ago
uses Unicode CLDR rules for formatting plurals. These rules are number pluralization classifier functions (one for each locale) which can tell if a number should be treated as zero
, one
, two
, few
, many
or other
. Knowing how these pluralization rules work is not required but anyway here are some links for curious advanced readers: rules explanation, list of rules for all locales, converting those rules to javascript functions. These pluralization functions can be found as plural
properties of a locale data.
When given future dates .format()
produces the corresponding output, e.g. "in 5 minutes", "in a year", etc.
The default locale is en
and can be changed: TimeAgo.defaultLocale = 'ru'
.
There is also a React component built upon this library which autorefreshes itself.
Intl
global object is not required for this library, but it may be required if you choose to use the built-in twitter
style (though it will fall back to the default style if Intl
is not available).
Intl
is present in all modern web browsers and is absent from some of the old ones: Internet Explorer 10, Safari 9 and iOS Safari 9.x (which can be solved using Intl
polyfill).
Node.js starting from 0.12
has Intl
built-in, but only includes English locale data by default. If your app needs to support more locales than English on server side then you'll need to use Intl
polyfill.
Applying Intl
polyfill:
npm install intl@1.2.4 --save
npm install intl-locales-supported --save
Node.js
import IntlPolyfill from 'intl'
import intlLocalesSupported from 'intl-locales-supported'
if (typeof Intl === 'object') {
if (!intlLocalesSupported(['ru', 'fr', ...])) {
Intl.NumberFormat = IntlPolyfill.NumberFormat
Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat
}
}
else {
global.Intl = IntlPolyfill
}
Web browser: same as for Node.js with global
replaced with window
.
After cloning this repo, ensure dependencies are installed by running:
npm install
This module is written in ES6 and uses Babel for ES5 transpilation. Widely consumable JavaScript can be produced by running:
npm run build
Once npm run build
has run, you may import
or require()
directly from
node.
After developing, the full test suite can be evaluated by running:
npm test
When you're ready to test your new functionality on a real project, you can run
npm pack
It will build
, test
and then create a .tgz
archive which you can then install in your project folder
npm install [module name with version].tar.gz
FAQs
Localized relative date/time formatting
The npm package javascript-time-ago receives a total of 197,934 weekly downloads. As such, javascript-time-ago popularity was classified as popular.
We found that javascript-time-ago demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.