Zack Herbert Zack Herbert - 2 months ago 26
Javascript Question

How to use moment.js to subtract two times and compare it to a number of minutes

I am working on implementing a JS function to mirror a function that I have in my Ruby code.

The Ruby Code:

def autoextending?
online_only? && ((actual_end_time - Time.now) <= autoextend_increment.minutes)
end


The JS Code:

item.autoextending = function() {
var self = this;
var end_time = moment(self.actual_end_time);
return (self.online_only && self.status == "accepting_bids" && ((end_time - moment()) <= self.autoextend_increment*60));
};


A little information:


  • self.autoextend_increment will return a number such as 5 which represents a number of minutes.

  • I need the evaluation of
    (end_time - moment())
    to return the difference as a number of seconds so that I can compare it to the
    autoextend_increment
    properly



Any help is appreciated.

Answer

moment uses Date under the hood, which as a raw value is represented as time in milliseconds since epoch. So right away we know that arithmetic from moment will yield values in milliseconds:

item.autoextending = function() {
    var self = this;
    var end_time = moment(self.actual_end_time);
    return (self.online_only && self.status == "accepting_bids" && (((end_time - moment()) / (1000 * 60)) <= self.autoextend_increment));
};

((end_time - moment()) / (1000 * 60)) will give you a value in minutes (1000 milliseconds in a second, 60 seconds in a minute).

You said self.autoextend_increment is already in minutes, so no additional arithmetic is needed. If you really want to compare in seconds, you can: ((end_time - moment()) / 1000) <= self.autoextend_increment * 60

You could have also written your conversion as (end_time - moment()) / 6000 but I broke down the figures for demonstration purposes.