Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda