How to compare two datetime using js?

1

How can I compare 2 date times ?, example: '2017-12-06 15:00' and '2017-12-06 14:00' to use it in a conditional.

this is my code:

var inicio  = '2017-12-06 15:00';
var termino = '2017-12-06 14:00';

if(inicio > termino){
  alert("Error!");
};

But the comparison does not do it correctly.

    
asked by C.Meza 06.12.2017 в 18:39
source

4 answers

1

Good afternoon, I found a solution using the moment.js library thanks to a comment from a user, I leave the code for how to solve it

function compare(dateTimeA, dateTimeB) {
    var momentA = moment(dateTimeA,"YYYY/MM/DD HH:mm");
    var momentB = moment(dateTimeB,"YYYY/MM/DD HH:mm");
    if (momentA > momentB) return 1;
    else if (momentA < momentB) return -1;
    else return 0;
}

alert(compare("2017-12-06 13:00", "2017-12-06 14:00"));

since thank you very much everyone for contributing to the solution, greetings.

    
answered by 06.12.2017 / 19:49
source
0

To compare two dates, we must first take into account that the objects are of Date type .

var f1 = new Date(2017, 12, 31);
var f2 = new Date(2018, 1, 1);

You can use the following operators perfectly, you will only find problems with the operator ==

>
<
>=
<=

If we execute the following comparison, we are checking that both objects are equal, which is false.

if(f1 == f2){
   return true;
}

To check if both dates are the same we must use the method .getTime()

if(f1.getTime() == f2.getTime()){
    return true;
}
    
answered by 06.12.2017 в 18:48
0

By the way, you have two string in date format. First you must create two date elements, and then make the comparison between dates.

function CompararFechas()
{
	//Comprobamos que tenga formato correcto
	var fecha_aux = document.getElementById("Fecha").value.split("-");
 	var Fecha1 = new Date(parseInt(fecha_aux[2]),parseInt(fecha_aux[1]-1),parseInt(fecha_aux[0]));
 
 	//Comprobamos si existe la fecha
	if (isNaN(Fecha1)){
		alert("Fecha introducida incorrecta");
		return false;
	}
	else{
		alert("La fecha que has introducido es "+Fecha1);
	}
}
//var inicio  = '2017-12-06 15:00';
//var termino = '2017-12-06 14:00';
<html>
    <head>
        <title>Comparacion Fechas JS</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
            <table>
                <tr>
                    <th align="left">Introduce Fecha:</th>
                    <th><input id="Fecha" type="text" /></th>
                    <th><input type="button" value="Enviar" onClick="CompararFechas()"/></th>
                </tr>
            </table>	
    </body>
</html>

Since you have your date ready, now if the comparison between dates is made. You can do it between each element or the complete date with the function of getTime () to get the arithmetic value of the dates.

function CompararFechas()
{
	//Comprobamos que tenga formato correcto
	var fecha_aux = document.getElementById("Fecha").value.split("-");
 	var Fecha1 = new Date(parseInt(fecha_aux[2]),parseInt(fecha_aux[1]-1),parseInt(fecha_aux[0]));
  var fecha_aux2 = document.getElementById("Fecha").value.split("-");
 	var Fecha2 = new Date(parseInt(fecha_aux2[2]),parseInt(fecha_aux2[1]-1),parseInt(fecha_aux2[0]));
 	//Comprobamos si existe la fecha
	if (isNaN(Fecha1)){
		alert("Fecha introducida incorrecta");
		return false;
	}
	else{
		alert("La fecha que has introducido es "+Fecha1);
	}
  
  if(Fecha1.getTime() == Fecha2.getTime()){
    alert("Ambas fechas son iguales");
}
  
var AnyoFecha = Fecha1.getFullYear();
var MesFecha = Fecha1.getMonth();
var DiaFecha = Fecha1.getDay();
 
var AnyoHoy = Fecha2.getFullYear();
var MesHoy = Fecha2.getMonth();
var DiaHoy = Fecha2.getDay();
 
if (AnyoFecha < AnyoHoy){
    alert ("La fecha introducida es anterior a Hoy");
}
else{
    if (AnyoFecha == AnyoHoy && MesFecha < MesHoy){
        alert ("La fecha introducida es anterior a Hoy");			
    }
    else{
        if (AnyoFecha == AnyoHoy && MesFecha == MesHoy && DiaFecha < DiaHoy){
            alert ("La fecha introducida es anterior a Hoy");
        }
        else{
            if (AnyoFecha == AnyoHoy && MesFecha == MesHoy && DiaFecha == DiaHoy){
                 alert ("Has introducido la fecha de Hoy");
            }
            else{
                alert ("La fecha introducida es posterior a Hoy");
            }
        }
    }
}
}
<html>
    <head>
        <title>Comparacion Fechas JS</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
            <table>
                <tr>
                    <th align="left">Introduce Fecha:</th>
                    <th><input id="Fecha" type="text" /></th>
                    <th><input id="Fecha2" type="text" /></th>
                    <th><input type="button" value="Enviar" onClick="CompararFechas()"/></th>
                </tr>
            </table>	
    </body>
</html>
    
answered by 06.12.2017 в 19:03
0

Alternative with JavaScript , convert the data in whole and compare them numerically, as their date format are the same and the hours are in 24H can work:

var inicio  = '2016-12-06 13:00';
var termino = '2017-11-06 14:00';

//quita (-),(:), espacios y los comvierte en entero
inicio = parseInt(inicio.replace(/-|:|\s/g , ""));
termino = parseInt(termino.replace(/-|:|\s/g , ""));

//compara que dato es mayor
if(inicio > termino){
  alert("inicio mayor que termino");
}else{
  alert("termino mayor que inicio");
}
    
answered by 06.12.2017 в 20:33