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

214
Vistas
moment js subtract'ed date equal another date by <= returns false instead true

I am very much confused by following behavior while comparing two dates:

moment(date).format('YYYY-MM-DD')
'2022-07-15'
moment(range.end).subtract(1, 'days').format('YYYY-MM-DD')
'2022-07-15'

why then:

moment(date) <= moment(range.end).subtract(1, 'days')

enter image description here

what should be the proper way compare this days for date being equal, gt, lt using momentjs?

UPDATE:

using isSameOrBefore after having both dates wrapped in moment:

date.format('YYYY-MM-DD')
'2022-07-15'
range.end
'2022-07-16'
moment(date).format('YYYY-MM-DD')
'2022-07-15'
moment(range.end).subtract(1, 'days').format('YYYY-MM-DD')
'2022-07-15'
moment(date).isSameOrBefore(moment(range.end).subtract(1, 'days'))
false

I guess I got it:

moment(date).isSameOrBefore(moment(range.end).subtract(1, 'days'), 'day')

providing level of granularity of check to day seems to do the trick.

docs

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Moment gives us isBefore, isAfter, isSame, isSameOrBefore etc. to make these comparisons.

var a = moment().format('YYYY-MM-DD')

var b = moment().subtract(1, 'days').format('YYYY-MM-DD')

console.log(moment(a).isAfter(b));
console.log(moment(a).isBefore(b));
console.log(moment(a).isSameOrBefore(b));
// sometimes you may want to provide precision level of comparision like this:
console.log(moment(a).isSameOrBefore(b, 'day'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

about 4 years ago · Santiago Gelvez 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