2.2.0 • Published 4 years ago

s-ago v2.2.0

Weekly downloads
5,903
License
MIT
Repository
github
Last release
4 years ago

s-ago

NPM version Dependencies build status NPM license

This is the smallest, fully unit tested module to convert Date objects into human readable relative timestamps, such as '4 minutes ago', 'yesterday', 'tomorrow', or 'in 3 months'. All in 22 lines of TypeScript.

You can optionally specify the maximum unit (eg. hour, day, week) so instead of outputting '2 weeks ago' you will see '14 days ago'.

Usage

var ago = require('s-ago');

var now = new Date();
var yesterday = new Date(now.getTime() - (24 * 60 * 60 * 1000));
var hoursAgo = new Date(now.getTime() - (6 * 60 * 60 * 1000));
var yesterday = new Date(now.getTime() - (24 * 60 * 60 * 1000));
var tomorrow = new Date(now.getTime() + (6 * 60 * 60 * 1000));
var inSixHours = new Date(now.getTime() + (6 * 60 * 60 * 1000));
var inTwoWeeks = new Date(now.getTime() + (2 * 7 * 24 * 60 * 60 * 1000));

// present
ago(now); // 'just now'

// past
ago(yesterday); // 'yesterday'
ago(hoursAgo); // '6 hours ago'

// future
ago(inSixHours); // 'in 6 hours'
ago(tomorrow); // 'tomorrow'

// max unit
ago(inTwoWeeks);  // 'in 2 weeks'
ago(inTwoWeeks, 'day'); // 'in 14 days'

Output is as follows:

TimeOutputFuture output
Less than 1 minutejust nowjust now
1-2 minutesa minute agoin a minute
2-46 minutes# minutes agoin # minutes
46 minutes - 2 hoursan hour agoin an hour
2-20 hours# hours agoin # hours
20-48 hoursyesterdaytomorrow
2-6 dayslast weekin a week
7-28 days# weeks agoin # weeks
28 days - 2 monthslast monthin a month
2-11 months# months agoin # months
11-23 monthslast yearin a year
2+ years# years agoin # years