Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Javascript - comparing two dates ( minus X days) to see whether it's true or false

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 !

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

^ 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");
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!