How to make operations with Dates/Hours in Javascript?

前端 未结 3 1274
小鲜肉
小鲜肉 2021-01-28 14:03

I have to subtract two hours passed by the user in the format \'HH: MM\' and the result has to divide by the number of feeds on the day and set the exact hours that it should fe

3条回答
  •  再見小時候
    2021-01-28 14:25

    In most browsers, Dates support the subtraction operator, which will return the number of milliseconds between them. Alternatively, you can get a timestamp (the number of milliseconds since the Unix Epoch) by calling .getTime(). This second option may be a bit safer and have broader support, though I haven't found an authoritative source or document to corroborate.

    The result will be positive if the Date on the left is after the date on the right and negative if it is before. If you want the difference represented as a positive number either way then you can use Math.abs().

    var x = new Date(2019, 0, 1);
    var y = new Date(2019, 0, 1, 5, 45);
    
    // NOTE: You haven't specified how to handle "negative" differences
    var diff = Math.abs(y.getTime() - x.getTime());
    
    // From here it's simple arithmetic:
    var hours = Math.floor(diff / 3600000);
    var minutes = Math.floor((diff % 3600000) / 60000);
    
    // NOTE: Differences greater than 99:59 will be truncated!
    console.log( ("00" + hours).slice(-2) + ":" + ("00" + minutes).slice(-2) )

    As for the rest of your question:

    the result has to divide by the number of feeds on the day and set the exact hours that it should feed.

    I have no idea what this means. Hopefully the date logic is enough for you to get started.

提交回复
热议问题