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