简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM