Skip to content

Commit

Permalink
error handling to prevent future dates
Browse files Browse the repository at this point in the history
  • Loading branch information
jackie1santana committed Jul 18, 2024
1 parent 1d18059 commit 6ef24b0
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
3 changes: 0 additions & 3 deletions __test__/showTimeAgo.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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());
Expand Down

0 comments on commit 6ef24b0

Please sign in to comment.