js-time-ago
v3.1.0
Published
A simple and easy library to determine how long ago an event occurred or will occur
Downloads
36
Maintainers
Readme
js-time-ago
A simple and easy library to determine how long ago an event occurred or will occur
Language support
Currently there is support for three languages:
- en - English
- es - Spanish
- pt - Portuguese
you will get a result like this:
English by fault
- right now
- 10 seconds ago
- in 10 second
- 1 minute ago
- in 1 minute
- 1 hour ago
- in 1 hour
- 1 day ago
- in 1 day
- 1 week ago
- in 1 week
- 1 month ago
- in 1 month
- 1 year ago
- in 1 year
Installation 🔧
This package is available through npm registration.
npm install js-time-ago
Usage 🚀
import { format } from 'js-time-ago';
// we specify the date and the language in which we will receive the answer
format( Date.now(), 'en' )
.then( console.log );
// right now
// support async / await
(async () => {
const response = await format( Date.now() + 2 * 60 * 1000, 'es' );
console.log( response );
// dentro de 2 minutos
})();
const getTime = async (time, local) => {
const response = await format( time, local );
console.log( response );
// 1 mês atrás
};
getTime( Date.now() - 1 * 4 * 7 * 24 * 60 * 60 * 1000, 'pt' );
// use with angular pipe
import { Pipe, PipeTransform } from '@angular/core';
import { format } from 'js-time-ago';
@Pipe({
name: 'jstimeago'
})
export class JsTimeAgoPipe implements PipeTransform {
async transform(date: number | Date): Promise<string> {
return await format( date, 'en' );
}
}
// import pipe in declarations and use it in html component
<span>{{ date | jstimeago | async }}</span>
Styles
List of supported "styles".
Round
format( Date.now(), 'en', 'round' ).then( console.log );
// right now
format( Date.now() - 1 * 1000, 'en', 'round' ).then( console.log );
// 1 second ago
format( Date.now() - 1 * 60 * 60 * 1000, 'en', 'round' ).then( console.log );
// 1 hour ago
format( Date.now() - 1 * 7 * 24 * 60 * 60 * 1000, 'en', 'round' ).then( console.log );
// 1 week ago
Mini
format( Date.now(), 'en', 'mini' ).then( console.log );
// 0s
format( Date.now() - 1 * 1000, 'en', 'mini' ).then( console.log );
// 1s
format( Date.now() - 1 * 60 * 60 * 1000, 'en', 'mini' ).then( console.log );
// 1h
format( Date.now() - 1 * 7 * 24 * 60 * 60 * 1000, 'en', 'mini' ).then( console.log );
// 1week