Skip to content

Commit ab0faef

Browse files
Add rounding to nearest hour
1 parent a7848fe commit ab0faef

2 files changed

Lines changed: 22 additions & 9 deletions

File tree

src/util/TimeUtil.js

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ export default {
9797
/**
9898
* @method formatDateToDeviceAssuranceGracePeriodExpiryLocaleString
9999
* Conversion from a Date object to a locale string that mimics Okta's `short-with-timezone` format
100+
* but rounded down to the nearest hour
100101
* e.g. new Date(2024-09-05T00:00:00.000Z) -> 09/05/2024, 8:00 PM EDT
101102
*
102103
* @param {Date} date The Date object for the grace period expiry
@@ -106,15 +107,20 @@ export default {
106107
formatDateToDeviceAssuranceGracePeriodExpiryLocaleString: (date, languageCode) => {
107108
try {
108109
// Invalid Date objects will return NaN for valueOf()
109-
return date && !isNaN(date.valueOf()) && languageCode !== null ? date.toLocaleString(languageCode, {
110-
year: 'numeric',
111-
month: '2-digit',
112-
day: '2-digit',
113-
hour: 'numeric',
114-
minute: 'numeric',
115-
timeZoneName: 'short',
116-
})
117-
: null;
110+
if (date && !isNaN(date.valueOf()) && languageCode !== null) {
111+
// Round down the date to the nearest hour
112+
date.setMinutes(0, 0, 0);
113+
return date.toLocaleString(languageCode, {
114+
year: 'numeric',
115+
month: '2-digit',
116+
day: '2-digit',
117+
hour: '2-digit',
118+
minute: '2-digit',
119+
timeZoneName: 'short',
120+
});
121+
} else {
122+
return null;
123+
}
118124
} catch (e) {
119125
// If `languageCode` isn't in a valid format `toLocaleString()` will throw a `RangeError`
120126
return null;

test/unit/spec/TimeUtil_spec.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,13 @@ describe('util/TimeUtil', function() {
112112
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:00:00Z'), languageCode)).toEqual('09/05/2024, 12:00 AM UTC');
113113
});
114114

115+
it('rounds down to the nearest hour', () => {
116+
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:01:01Z'), languageCode)).toEqual('09/05/2024, 12:00 AM UTC');
117+
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:30:30Z'), languageCode)).toEqual('09/05/2024, 12:00 AM UTC');
118+
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T23:59:59Z'), languageCode)).toEqual('09/05/2024, 11:00 PM UTC');
119+
});
120+
121+
115122
it('falls back to default locale if `languageCode` is undefined', () => {
116123
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:00:00Z'), undefined)).toEqual('09/05/2024, 12:00 AM UTC');
117124
});

0 commit comments

Comments
 (0)