Skip to content

Commit

Permalink
Add rounding to nearest hour
Browse files Browse the repository at this point in the history
  • Loading branch information
trevoring-okta committed Sep 4, 2024
1 parent a7848fe commit ab0faef
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/util/TimeUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export default {
/**
* @method formatDateToDeviceAssuranceGracePeriodExpiryLocaleString
* Conversion from a Date object to a locale string that mimics Okta's `short-with-timezone` format
* but rounded down to the nearest hour
* e.g. new Date(2024-09-05T00:00:00.000Z) -> 09/05/2024, 8:00 PM EDT
*
* @param {Date} date The Date object for the grace period expiry
Expand All @@ -106,15 +107,20 @@ export default {
formatDateToDeviceAssuranceGracePeriodExpiryLocaleString: (date, languageCode) => {
try {
// Invalid Date objects will return NaN for valueOf()
return date && !isNaN(date.valueOf()) && languageCode !== null ? date.toLocaleString(languageCode, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: 'numeric',
minute: 'numeric',
timeZoneName: 'short',
})
: null;
if (date && !isNaN(date.valueOf()) && languageCode !== null) {
// Round down the date to the nearest hour
date.setMinutes(0, 0, 0);
return date.toLocaleString(languageCode, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
timeZoneName: 'short',
});
} else {
return null;
}
} catch (e) {
// If `languageCode` isn't in a valid format `toLocaleString()` will throw a `RangeError`
return null;
Expand Down
7 changes: 7 additions & 0 deletions test/unit/spec/TimeUtil_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ describe('util/TimeUtil', function() {
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:00:00Z'), languageCode)).toEqual('09/05/2024, 12:00 AM UTC');
});

it('rounds down to the nearest hour', () => {
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:01:01Z'), languageCode)).toEqual('09/05/2024, 12:00 AM UTC');
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:30:30Z'), languageCode)).toEqual('09/05/2024, 12:00 AM UTC');
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T23:59:59Z'), languageCode)).toEqual('09/05/2024, 11:00 PM UTC');
});


it('falls back to default locale if `languageCode` is undefined', () => {
expect(TimeUtil.formatDateToDeviceAssuranceGracePeriodExpiryLocaleString(new Date('2024-09-05T00:00:00Z'), undefined)).toEqual('09/05/2024, 12:00 AM UTC');
});
Expand Down

0 comments on commit ab0faef

Please sign in to comment.