Implement smart-date-format-helper
Add a helper that knows how to format past dates in a smart way. When less than a week ago we will use relative date strings - for dates older than a week we will use a friendly human-readable format. This matches best practices we want to adhere to based on what Terraform did for date-formatting.
This commit is contained in:
parent
bd5b47bfa8
commit
be604a2828
|
@ -0,0 +1,48 @@
|
||||||
|
import Helper from '@ember/component/helper';
|
||||||
|
import { inject as service } from '@ember/service';
|
||||||
|
|
||||||
|
const MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;
|
||||||
|
const MILLISECONDS_IN_WEEK = MILLISECONDS_IN_DAY * 7;
|
||||||
|
/**
|
||||||
|
* A function that returns if a date is within a week of the current time
|
||||||
|
* @param {*} date - the date to check
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
function isNearDate(date) {
|
||||||
|
const now = new Date();
|
||||||
|
const aWeekAgo = now - MILLISECONDS_IN_WEEK;
|
||||||
|
const aWeekInFuture = now + MILLISECONDS_IN_WEEK;
|
||||||
|
|
||||||
|
return date >= aWeekAgo && aWeekInFuture;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class SmartDateFormat extends Helper {
|
||||||
|
@service temporal;
|
||||||
|
@service intl;
|
||||||
|
|
||||||
|
compute([value], hash) {
|
||||||
|
const fallback = hash.fallback || 'None yet';
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
|
return {
|
||||||
|
isNearDate: false,
|
||||||
|
relative: fallback,
|
||||||
|
friendly: fallback,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
isNearDate: isNearDate(value),
|
||||||
|
relative: `${this.temporal.format(value)} ago`,
|
||||||
|
friendly: this.intl.formatTime(value, {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: 'numeric',
|
||||||
|
second: 'numeric',
|
||||||
|
hourCycle: 'h24',
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue