0

I want to compare a init time with current time and results are weird.

From a String a build a date like shown:

fechIni = "2019-02-07"
timeIni = "17:40"
var datepartsIni = fechIni.split("-");
var horapartsIni = timeIni.split(":");
var dateIni = new Date(datepartsIni[0], datepartsIni[1], datepartsIni[2], horapartsIni[0], horapartsIni[1]);

if print dateIni, I got something like: Thu Mar 07 2019 17:40:00 GMT-0300 (hora de verano de Chile) Witch I think is right.

Then, I compare that date with current date (for not allowing doing something).

var currentdate = new Date();

When I compared them, (imagine dateIni is earlier than currentdate) with something like this:

if (dateIni > currentdate) {... do stuff ...}

I got true when it should be false. I have try with .valueOf(), convert to milis, convert to epoch and calculating difference... but I can't do the trick.

I attach a screenshot of console output and code.

Code

Code2

UPDATE: Solved!! The trick was setting the date:

var dateFin = new Date(datepartsFin[0], datepartsFin[1] - 1, datepartsFin[2], horapartsFin[0], horapartsFin[1]);

Instead of

var dateFin = new Date(datepartsFin[0], datepartsFin[1], datepartsFin[2], horapartsFin[0], horapartsFin[1]); //WRONG in my case
Carol
  • 553
  • 2
  • 10
  • 24
  • 2
    I don't understand the problem. Mar 07 is indeed > Feb 07. What did you expect? – geoidesic Feb 07 '19 at 21:13
  • 1
    The months are indexed from 0 in date. So "02" means March and not February – wolfram42 Feb 07 '19 at 21:14
  • i would parse it as a js-known string, like ISO or GMT, so that timezones aren't wrong like when you feed Date() a bunch of numbers. – dandavis Feb 07 '19 at 21:15
  • I didn't realised of that @wolfram42 thanks!! – Carol Feb 07 '19 at 21:16
  • I was obfuscated on day and time than I didn't realised of month. Developing storys... – Carol Feb 07 '19 at 21:17
  • Confused as you say that (dateIni > currentdate) is true but should be false. Your dateIni is in the future not the past. The valueOf returns a number that is greater the further away from the epoch (or 0). So this means that dates in the future are a greater value than the present. Your if statement should return true. – RoboYak Feb 07 '19 at 21:21

0 Answers0