From ecfb17bba0088a13cff09271b9ee91c69f62e92b Mon Sep 17 00:00:00 2001 From: Michael Klein Date: Mon, 10 Oct 2022 14:56:00 +0200 Subject: [PATCH] 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. --- .../app/helpers/smart-date-format.js | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 ui/packages/consul-ui/app/helpers/smart-date-format.js diff --git a/ui/packages/consul-ui/app/helpers/smart-date-format.js b/ui/packages/consul-ui/app/helpers/smart-date-format.js new file mode 100644 index 0000000000..c195157ad2 --- /dev/null +++ b/ui/packages/consul-ui/app/helpers/smart-date-format.js @@ -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', + }), + }; + } +}