s-ago
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 = ; var now = ;var yesterday = now - 24 * 60 * 60 * 1000;var hoursAgo = now - 6 * 60 * 60 * 1000;var yesterday = now - 24 * 60 * 60 * 1000;var tomorrow = now + 6 * 60 * 60 * 1000;var inSixHours = now + 6 * 60 * 60 * 1000;var inTwoWeeks = now + 2 * 7 * 24 * 60 * 60 * 1000; // present; // 'just now' // past; // 'yesterday'; // '6 hours ago' // future; // 'in 6 hours'; // 'tomorrow' // max unit; // 'in 2 weeks'; // 'in 14 days'
Output is as follows:
Time | Output | Future output |
---|---|---|
Less than 1 minute | just now |
just now |
1-2 minutes | a minute ago |
in a minute |
2-46 minutes | # minutes ago |
in # minutes |
46 minutes - 2 hours | an hour ago |
in an hour |
2-20 hours | # hours ago |
in # hours |
20-48 hours | yesterday |
tomorrow |
2-6 days | last week |
in a week |
7-28 days | # weeks ago |
in # weeks |
28 days - 2 months | last month |
in a month |
2-11 months | # months ago |
in # months |
11-23 months | last year |
in a year |
2+ years | # years ago |
in # years |