Skip to content

Commit 578453c

Browse files
committed
intl - since
1 parent 4e3d537 commit 578453c

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@rightech/utils",
3-
"version": "0.1.14",
3+
"version": "0.1.15",
44
"description": "",
55
"main": "index.js",
66
"private": false,

src/format.js

+32-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const DEFAULT_FALLBACK = '-';
2121
const DEFAULT_LOCALE = 'en';
2222
const DEFAULT_24H_LOCALE = 'en-GB';
2323

24+
const timeOf1 = timeOf(1);
2425

2526
let fallback = DEFAULT_FALLBACK;
2627
let currentLocale = DEFAULT_LOCALE;
@@ -125,6 +126,35 @@ function currency(value, currency, locale) {
125126
return new Intl.NumberFormat(locale, style).format(value);
126127
}
127128

129+
function sinceUnitBestFit(ms) {
130+
ms = Math.abs(ms);
131+
if (ms < timeOf1.minutes) {
132+
return 'second';
133+
}
134+
if (ms < timeOf1.hours) {
135+
return 'minute';
136+
}
137+
if (ms < timeOf1.days) {
138+
return 'hour';
139+
}
140+
return 'day';
141+
}
142+
143+
function since(value, locale) {
144+
if (typeof value === 'string') {
145+
value = +value;
146+
}
147+
if (!value || isNaN(value)) {
148+
return fallback;
149+
}
150+
value = value - getLocalTime();
151+
const unit = sinceUnitBestFit(value);
152+
const bestValue = Math.floor(value / timeOf1[`${unit}s`]);
153+
154+
return getIntl('RelativeTimeFormat', 'auto', locale, { numeric: 'auto' })
155+
.format(bestValue, unit);
156+
}
157+
128158
/*
129159
function normalize(term, separator) {
130160
term = (term || '').toString();
@@ -161,5 +191,6 @@ module.exports = {
161191
timeSpan,
162192
number,
163193
currency,
164-
percent
194+
percent,
195+
since
165196
};

0 commit comments

Comments
 (0)