I am trying to execute a code if a date (from a cookie) is older than about 2 days. More or less, it doesnt have to be precise.
The cookie value is : 2022-06-27T23:28:02.816Z
function getCookie(name) {
var value = "; " document.cookie;
var parts = value.split("; " name "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
Using :
getCookie(name) and : .slice(0, 10);
Returns : 2022-06-27 Therefore I now have a YYYY-MM-DD value
var stuff_cookiename = getCookie("cookiename").slice(0, 10);
Converting to a date format :
var t_date_refuscmp_todate = Date.parse(stuff_cookiename);
I now have something like this : 1656288000000
Now I want to compare it NOW's date - 2 days So I do :
var t_date_verif = new Date();
var t_date_verif_format = tc_date_verif.setDate(tc_date_verif.getDate() - 2);
Which brings me something like : 1656199936800
=====================
But if i compare my cookiedate vs todaysdate -2 days, it doesnt always seem to be working correctly.
t_date_refuscmp_todate < t_date_verif_format !!!
Any idea of what I am not doing right? Maybe there is something a lot easier to do :)
Thanks !
CodePudding user response:
Idea
Parse the cookie and the current datetime, convert it into epoch ms, sompute the difference in days.
Code
let s_dtCookie = "2022-06-27T23:28:02.816Z"
, n_epochCookie = (new Date(s_dtCookie)).getTime()
, n_epochNow = (new Date()).getTime()
, n_deltaDays = (n_epochNow - n_epochCookie) / (24 * 3600 * 1000)
;
console.log(`Cookie time '${s_dtCookie}' is ${n_deltaDays} days in the past.`);
Reference
MDN JS docs, Date.getTime() section.
CodePudding user response:
^ A more specific(to your question)and simpler answer in my opinion
var diff = Date.now() - new Date("2022-06-25T23:28:02.816Z");
if(diff <= 1000 * 60 * 60 * 24 * 2){
console.log("less than 2 days old");
}else{
console.log("more than 2 days old");
}