From 6ef24b0025c95afa666611fbd0b0a797880c96d4 Mon Sep 17 00:00:00 2001 From: jackie1santana Date: Thu, 18 Jul 2024 12:24:00 -0500 Subject: [PATCH] error handling to prevent future dates --- __test__/showTimeAgo.spec.js | 3 --- index.js | 9 ++++++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/__test__/showTimeAgo.spec.js b/__test__/showTimeAgo.spec.js index f39e368..e9136cf 100644 --- a/__test__/showTimeAgo.spec.js +++ b/__test__/showTimeAgo.spec.js @@ -77,9 +77,6 @@ test('Test Date for the start of Unix Epoch (January 1, 1970)', () => { expect(showTimeAgo(epochStart)).toBe(`${epochYears} years ago`); }); -test('Test Date for a future date', () => { - expect(showTimeAgo(futureDate)).toBe('now'); -}); test('Test Date for just a few seconds ago', () => { expect(showTimeAgo(fewSecondsAgo)).toContain('seconds ago'); diff --git a/index.js b/index.js index 895e285..cf6154b 100644 --- a/index.js +++ b/index.js @@ -56,6 +56,12 @@ function showtimeago(dateParam) { function timeAgo(dateParam) { const date = validateDateParam(dateParam); const now = new Date(); + + // Check if the date is in the future + if (date > now) { + throw new Error("Invalid date: The provided date is in the future."); + } + const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000 const YEAR_IN_MS = 365.25 * DAY_IN_MS; // Account for leap years const yesterday = new Date(now.getTime() - DAY_IN_MS); @@ -129,7 +135,8 @@ function showtimeago(dateParam) { throw new Error(error.message); } } -// console.log(showtimeago("2024-07-18T17:12:00.000Z")); + +console.log(showtimeago("2024-07-18T17:12:00.000Z")); // Example usage to test with current time // const now = new Date(); // console.log("Current time:", now.toISOString());