Compare fechas de JavaScript (día/minuto/hora/antes/después), con ejemplos

Siguiendo con nuestro artículo sobre sumar y restar tiempo de fechas en JavaScript , aquí se explica cómo comparar dos objetos de fecha de JavaScript.

Este artículo explorará la comparación de fechas/horas con diferentes niveles de granularidad, desde fechas que son un mes exacto hasta fechas que caen en el mismo año.

Uso de operadores booleanos

Los objetos de fecha nativos de Javascript se pueden comparar mediante operadores booleanos/de comparación estándar, lo que le permite comparar fechas comprobando si son iguales, no iguales, mayores que, menores que, iguales o mayores que, o iguales o menores que entre sí.

Comprobar si las fechas son idénticas en Javascript

Comprobar la igualdad:

var date1 = new Date(); // Defaults to now
var date2 = new Date(); // Defaults to now

if(date1 == date2) {
    // Dates are the same
}

Comprobar si una fecha es anterior o posterior a otra

Simplemente use operadores de comparación booleanos estándar de JavaScript:

var date1 = new Date(); // Defaults to now
var date2 = new Date(); // Defaults to now

date1.setTime(date1.getTime() + (1 * 60 * 60 * 1000));  // Add an hour to date1

if(date1 > date2){
    // The time stored by date1 is after date2
}

if(date2 < date1){
    //The time stored by date2 is before date1
}

Comprobar si dos objetos de fecha comparten el mismo segundo, minuto, hora, día, mes, año

Cuando se utilizan comparaciones booleanas en objetos de fecha, se comparan hasta el milisegundo (1/1000 de segundo). Aquí se explica cómo comparar con diferentes unidades de tiempo:

var date1 = new Date(); // Defaults to now
var date2 = new Date(); // Defaults to now

date1.setTime(date1.getTime() + (1 * 60 * 60 * 1000));  // Add an hour to date1


# The getSeconds() method will return the seconds component of the date object from 0-59

# The getMinutes() method will return the minutes component of the date object from 0-59

# The getHours() method will return the hours component of the date object from 0-23

# The getDate() method will return the date (day in month) of the date object from 0-31

# The getMonth() method will return the month of the date object from 0-11 (Starting with January at 0)

# The getFullYear() method will return the year of the date object as a 4 digit number (eg 2021)

#So, to see if two dates share the same minute you could run

if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate() && date1.getHours() == date2.getHours() && date1.getMinutes() == date2.getMinutes() && ){
    // Dates are the same down to the minute
}

Momento JS

El último ejemplo de arriba es un poco complicado, hay una mejor manera.

Si crea aplicaciones que manejan fechas con frecuencia, Moment.js es invaluable.

Moment.js proporciona las herramientas para administrar fechas, zonas horarias, períodos de tiempo (el período entre dos fechas), todo convenientemente envuelto en clases fáciles de usar. La documentación es excelente y simplifica el manejo de fechas al mismo tiempo que lo hace más confiable.

Encuéntralo en:

https://momentjs.com/

Por ejemplo, para verificar si dos fechas caen en el mismo minuto, simplemente ejecutaría:

date1 = moment(); // Defaults to now
date2 = moment().add(7, 'days').add(2, 'minutes'); // Second date is 7 days and 2 minutes into the future

date1.isSame(date2, 'minute'); // Returns true if the dates are the same down to the minute