Know which date is higher in Javascript

2

I have 2 dates, one start and one end, I try to avoid that the start is greater than the end, apart from that I can not do it, I get rare years, days that are not ... etc.

                    console.log("start ", m , d ,  y);
                    console.log("fin ", m2 , d2, y2);

                    console.log("-------");

                    console.log("start", new Date(m, d, y));
                    console.log("fin", new Date(m2, d2, y2));

                    if (new Date(m, d, y) > new Date(m2, d2, y2)) {
                        format = false;
                        this.errorServer = true;
                        this.message = "La fecha de inicio no puede ser mayor que la fecha de fin.";
                    }

And the result:

As a result of this change, I do not get the error that the start date is longer ...

    
asked by EduBw 07.11.2018 в 11:30
source

2 answers

4

You are using the constructor badly, the correct thing is:

new Date (anyo, month, day);

But not only that, but the month starts at 0, then subtract 1:

console.log("start", new Date(2018, 10, 6)); //ayer, a día de la creación de esta respuesta.
console.log("fin", new Date()); //ahora

console.log(new Date(2018, 10, 6) > new Date());
console.log(new Date(2018, 10, 6) < new Date());

Not only the format is a bit strange, but also it is always UTC time, so the first line of the console shows me "2018-11-05T23:00:00.000Z" because I'm in UTC + 1, then the date 2018-11- 06 (00:00:00) has been delayed an hour.

    
answered by 07.11.2018 / 11:42
source
1

The problem is for the date object, which must be new Date (anio, indexMes, day) where indexMes must be indexed from 0 to 11. p>

The standard operators > , < , <= or >= can normally be used to compare the type Date , however if you want to use the operators == , != , === , and !== you must convert the date to milliseconds using the method getTime ().

var f1 = new Date();
var f2 = new Date(f1);
var iguales = f1.getTime() === f2.getTime();
var noIguales = f1.getTime() !== f2.getTime();

Official Documentation

    
answered by 07.11.2018 в 12:10