Hello, I have the following problem, I have a set of pairs of dates from different events, which I want to compare with a specific date.
For Date types , Javascript supports comparison operators >, <, ===, !==, >=, <=
to compare the entire date including date and times, which is correct, but this is where my problem arises, since I am only needing to compare only the dates without taking into account the time.
I simplify the problem in a simple example:
let inicio = new Date('2017-09-06T20:56:51');
let fin = new Date('2017-09-06T20:56:53');
// fecha a comparar si se encuentra en el rango
let comparador = new Date('2017-09-06T12:56:53');
// aqui es el problema
let resultado = inicio <= comparador && fin >= comparador
If you were to compare only by dates omitting the time, resultado
it would return true
.
Knowing that a day is 24 * 3600 * 1000 milliseconds, you can take the UNIX Time value of each date to get the number of days since the origin, ignoring the rest (the decimals):
The comparator function follows the standard: it returns 1 if the first parameter is greater than the second, 0 if they are equal, and -1 if the second parameter is greater than the first
There are several methods in Javascript that allow you to "split" the dates, that is, it sends you an integer numeric value. What occurs to me is that you do the comparison 3 times: first the year, then the month and finally the day. I leave you an example taken from https://www.w3schools.com/js/js_date_methods.asp
I Hope I've been helpful. Greetings.
I was thinking of a longer answer, but I think the simplest thing for your question is going to be to put the hours at 0. This way you will only compare the "dates" as you say.
Create the
Date
using only Y/m/d then compare, you will still have problems for the cases == , === , !=, !== The Solution is to add "+" in front of variables when comparing, Like this:Change the dates for more tests.
The sign
+
is necessary because theyDate
are objects and can never be equal in strict comparisons, putting the+a == +b
is equivalent to puttinga.valueOf() == b.valueOf()
I hope it helps you, good luck