0

When i try to compare end time not greater start time It return every time display NaN.

jQuery.validator.addMethod("checkTime", function(value, element, options) {

    var start_times = options.val(); #15:00
    var end_times = value;  #14:00
    var dtStart = new Date("1/1/2001 " + start_times);
    var dtEnd = new Date("1/1/2001 " + end_times);
    var difference_in_milliseconds = dtEnd - dtStart;
    console.log(difference_in_milliseconds);
    return difference_in_milliseconds > 0;
}, "End time should be grater than start time.");
Mayur Panchal
  • 659
  • 6
  • 25

2 Answers2

1

Maybe I am missing something (never used clockpicker, I suspect what you are adding is a number) but if you do:

(new Date("1/1/2001 "+67)) - (new Date("1/1/2001 "+767))

You get NaN. Wouldn't it be better to use:

var dtStart = Date.now() + start_times;
var dtEnd = Date.now() + end_times;

instead?

ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
  • `Date.now()` won't be based starting from 1/1/2001. – kshetline Apr 25 '18 at 08:10
  • It does not matter. He wants the difference – ibrahim tanyalcin Apr 25 '18 at 08:11
  • Then you could skip Date.now() too (which might change by 1 millisecond from one line to the next) and just subtract `start_times` from `end_times`. I suspect the whole point of messing with Date objects here is to somehow take advantage of date/time parsing. – kshetline Apr 25 '18 at 08:17
  • With that logic he could have skipped the new Date("1/1/2001 ".. as well. He is dealing with numbers after all, that's why he got that NaN in the first place. I wonder why he didn't just ask how the Date object parses instead of this example. But still his clockpicker is returning numbers. – ibrahim tanyalcin Apr 25 '18 at 08:21
1

You can extract hours, minutes and seconds from start_times and end_times firstly. And then make the changes in function as below:

jQuery.validator.addMethod("checkTime", function(value, element, options) {

var start_times = options.val();
var end_times = value;
var dtStart = new Date("1/1/2001");
dtStart.setHours('//Hours extracted from given start_times');
dtStart.setMinutes('//Minutes extracted from given start_times');
dtStart.setSeconds('//Seconds extracted from given start_times');

var dtEnd = new Date("1/1/2001");
dtEnd.setHours('//Hours extracted from given end_times ');
dtEnd.setMinutes('//Minutes extracted from given end_times ');
dtEnd.setSeconds('//Seconds extracted from given end_times '); 

var difference_in_milliseconds = dtEnd.getTime() - dtStart.getTime();
console.log(difference_in_milliseconds);
return difference_in_milliseconds > 0;
}, "End time should be grater than start time.");

The remaining things I kept as it is.

You can try this solution, Maybe it will work for you