From 93691e725f704560ea4a85647e3dce71fca236c0 Mon Sep 17 00:00:00 2001 From: William Martin Date: Fri, 30 Jun 2023 10:25:54 -0400 Subject: [PATCH] add daysRemaining util function and unit tests --- libs/common/src/platform/misc/utils.spec.ts | 21 +++++++++++++++++++++ libs/common/src/platform/misc/utils.ts | 9 +++++++++ 2 files changed, 30 insertions(+) diff --git a/libs/common/src/platform/misc/utils.spec.ts b/libs/common/src/platform/misc/utils.spec.ts index 5f7d63fee2..ac21f28d72 100644 --- a/libs/common/src/platform/misc/utils.spec.ts +++ b/libs/common/src/platform/misc/utils.spec.ts @@ -358,4 +358,25 @@ describe("Utils Service", () => { expect(actual.protocol).toBe("http:"); }); }); + + describe("daysRemaining", () => { + const now = new Date(2023, 9, 2); + jest.spyOn(Date, "now").mockReturnValue(now.getTime()); + + it("should return 0 for equal dates", () => { + expect(Utils.daysRemaining(new Date(2023, 9, 2))).toBe(0); + }); + + it("should return 0 for dates in the past", () => { + expect(Utils.daysRemaining(new Date(2020, 5, 11))).toBe(0); + expect(Utils.daysRemaining(new Date(2023, 9, 1))).toBe(0); + }); + + it("should handle future dates", () => { + expect(Utils.daysRemaining(new Date(2023, 9, 3))).toBe(1); + expect(Utils.daysRemaining(new Date(2023, 10, 12))).toBe(41); + // leap year + expect(Utils.daysRemaining(new Date(2024, 9, 2))).toBe(366); + }); + }); }); diff --git a/libs/common/src/platform/misc/utils.ts b/libs/common/src/platform/misc/utils.ts index 4c30822cc8..542c471bc8 100644 --- a/libs/common/src/platform/misc/utils.ts +++ b/libs/common/src/platform/misc/utils.ts @@ -538,6 +538,15 @@ export class Utils { return of(undefined).pipe(switchMap(() => generator())); } + /** + * Return the number of days remaining before a target date arrives. + * Returns 0 if the day has already passed. + */ + static daysRemaining(targetDate: Date): number { + const diffTime = targetDate.getTime() - Date.now(); + return Math.max(0, Math.round(diffTime / (1000 * 60 * 60 * 24))); + } + private static isAppleMobile(win: Window) { return ( win.navigator.userAgent.match(/iPhone/i) != null ||