Deepak Singh Deepak Singh - 1 year ago 83
Javascript Question

comparing between sets of time using moment.Js

I have defined a set of rules.

var rules = [
time : "12:00:00 pm",
time1 : "01:00:00 pm",
time : "01:00:00 pm",
time1 : "02:00:00 pm",
time : "02:00:00 pm",
time1 : "03:00:00 pm",
time : "03:00:00 pm",
time1 : "04:00:00 pm",
}, {
time : "04:00:00 pm",
time1 : "05:00:00 pm",

module.exports = rules;

Now I have got an array of data which consists of time I want to compare the dats with these rules and accordingly increment the value of status in the rules array.
I am using moment.Js to compare but its isAfter() and isBefore functions are not working for me as they should.

_.each(data, function(data){
// this comes from database where data.start_time consists of time

console.log(data.start_time); // Mon Oct 03 2016 12:40:36 GMT+0530 (India Standard Time)

var d = moment(data.start_time).format("hh:mm:ss a");
console.log(d); //12:40:36 pm

_.each(rules, function(rule){
console.log(rule.time); //12:00:00 pm

// Not able to reach here tried both isAfter
// isBefore everything.

Also if there is any faster or better way to do these kind of comparision please can you leave a gist below. I will check that out too.

gkb gkb
Answer Source

I tried to debug your code and have some observations -

  1. moment(d).isAfter - here, moment(d) does not have a method called "isAfter". This is a strange thing as it should have this method as per the documentation. I had to call the prototype method like below -

    var protoType = moment(start_time).__proto__;
    var isafter = protoType.isAfter(rule.time);

But, this led me to another issue - Maximum call stack size exceeded (Stack Overflowed ;p).

  1. Also, when I don't format the date in the way you are formatting (before calling the isAfter method), it works fine. Though I had a dummy value for rule.time variable. Moreover, I had to keep both the dates in the same format.

So, based on the observations, I would suggest you to not rip off the date part from the date by formatting it before comparing, since I guess it is required.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download