0

I have written the following code to check if the time difference is greater than 60 minutes. If the difference is less than 60 then false should return to console else true. Here when I use two time format (as mentioned in below code), the output is -1310 which is greater than -1380 but still it is returning the false . I am expecting true.

below is the code:

var currDay = new Date("2018-02-21T23:40:00+05:30");
console.log(currDay);
var nextDay = new Date("2018-02-22T01:50:00+05:30");
console .log(nextDay);

var currTime = (currDay.getHours() + ':' + currDay.getMinutes()).split(':');
console.log(currTime);
var currTimeHourToMinutes = parseInt(currTime[0]*60);
var currTimeMinutespart = parseInt(currTime[1]);
var TotalCurrTimeInMinutes = parseInt(currTimeHourToMinutes + currTimeMinutespart) ;
console.log(TotalCurrTimeInMinutes);

var deptTime = (nextDay.getHours() + ':' + nextDay.getMinutes()).split(':');
console.log(deptTime);
var depTimeHourToMinutes = parseInt(deptTime[0]*60);
var deptTimeMinutespart = parseInt(deptTime[1]);
var TotalDeptTimeInMinutes = parseInt(depTimeHourToMinutes+ deptTimeMinutespart);
console.log(TotalDeptTimeInMinutes);

var diffInArrivalAndDeptTime = TotalDeptTimeInMinutes-TotalCurrTimeInMinutes;
console.log(diffInArrivalAndDeptTime);
if((diffInArrivalAndDeptTime >= "60") &&  (diffInArrivalAndDeptTime > "-1380") ) 
{
   console.log("true1");
}

else
{
    console.log("false");
}

P.S. I am using Chrome Developer Snippets to run above code.

Ambika Tewari
  • 251
  • 3
  • 9
  • 4
    Firstly your logic to calculate the difference in minutes is massively over-complicated. It's a one-liner. See [this question](https://stackoverflow.com/questions/7709803/javascript-get-minutes-between-two-dates). With regard to why you always get a `false` outut, it's because you're comparing strings, not ints. – Rory McCrossan Feb 21 '18 at 11:33
  • Hi https://stackoverflow.com/users/519413/rory-mccrossan, Thank you for this , the simple script also worked the same for me but again how would I compare an output with the negative number ? using "" is treating the -1380 as string. – Ambika Tewari Feb 21 '18 at 11:45
  • 1
    you must convert the strings to numbers... parseInt() or parseFloat() – Calvin Nunes Feb 21 '18 at 11:47
  • Or just remove the quotes: eg. `diffInArrivalAndDeptTime >= 60` – Rory McCrossan Feb 21 '18 at 11:52
  • @AmbikaTewari Look at the answer with 90 upvotes (bottom one). That should do the trick. – Mark Baijens Feb 21 '18 at 11:58

1 Answers1

0

Subtracting two dates gives the difference in milliseconds. Divide by 60000 to get minutes.

date1 = new Date(*/some date*/);
date2 = new Date(*/some date*/);
diffInMinutes = Math.abs(date1 - date2) / 60000;
hashedram
  • 813
  • 7
  • 14