0

I'm trying to compare a date from a URL, with today's date. (I want to check, if the date from the URL, is within 28 days, from today's date).

Here's my code, which kinda works:

let params              = (new URL(document.location)).searchParams;
let from                = params.get('from');
let searchDate          = new Date(from);
let currentDate         = new Date();
let timeDiff            = Math.abs(currentDate.getTime() - searchDate.getTime());
let diffDays            = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log("from", from);
console.log("searchDate", searchDate);
console.log("currentDate", currentDate);
console.log("timeDiff", timeDiff);
console.log("timeDiff", timeDiff);

The problem I have, is that sometimes searchDate is being returned in US date format. And therefore, my diffDays is wrong.

Here's an example of the output/console.logs.
In this example, the from variable, (a string), is UK date format, which is what I want. (7th March 2021).

However, searchDate variable seems to read this, in US format, (3rd July 2021), which is not what I want. In this example, it should read as Sat 7th March 2021).

from 07-03-2021
searchDate Sat Jul 03 2021 00:00:00 GMT+0100 (British Summer Time)
currentDate Tue Jan 12 2021 09:55:48 GMT+0000 (Greenwich Mean Time)
timeDiff 14821451980
diffDays 172

In this example, the diffDays, should be 54 days.

What am I doing wrong?

Thanks, Reena

Reena Verma
  • 1,617
  • 2
  • 20
  • 47
  • You must either put string in proper format for `Date` or use momentJs to tell from what format you want to parse string. – Justinas Jan 12 '21 at 10:37
  • @Justinas - I can't use a framework for this. So is the problem `from` variable, is not in the correct date format? – Reena Verma Jan 12 '21 at 11:33
  • 1
    MomentJS is library, not framework. And yes, if your date is `07-03-2021` even you can't tell if it's `m-d-Y` or `d-m-Y` format deciding only from date string – Justinas Jan 12 '21 at 12:01

0 Answers0