Date difference in Javascript (ignoring time of day)

前端 未结 15 2208
无人共我
无人共我 2020-11-27 15:35

I\'m writing an equipment rental application where clients are charged a fee for renting equipment based on the duration (in days) of the rental. So, basically, (daily fee *

相关标签:
15条回答
  • 2020-11-27 16:22

    You could adjust the start date to midnight of the same day, then calculate the number of 24-hour periods between the dates. Then, you would take the ceiling or floor of that number depending on whether you want to count any part of a day as a whole day or not.

    function dateDiff(startDate, endDate) {
        // set startDate to the beginning of the day
        startDate = new Date(
            startDate.getFullYear(),
            startDate.getMonth(),
            startDate.getDate());
    
        return Math.floor((endDate - startDate) / 1000*60*60*24);
    }
    
    0 讨论(0)
  • 2020-11-27 16:25

    +up the example above that uses the UTC constructors. Without doing that, you'll be clobbered by Daylight Savings / Summer Hours.

    If you take the differences in some of them, it could wind up an hour short when crossing the DST line for your time zone in one direction (spring-forward, meaning in Feb asking for April, for example). When you floor N+23/24, you'll end up with N.

    The other direction (in October asking for December) should be fine, you'll end up an hour ahead which the floor() will deal with correctly.

    0 讨论(0)
  • 2020-11-27 16:28

    There is a bug in the given solutions!

    This applies to date differences where the time is disregarded AND you want an integer result, that is, whole number of days.

    In many of the examples above we see Math.floor other instances I've seen Math.ceil other places as well. These are done to round the result to an integer number of days. The problem is daylight savings time will give a wrong result in the fall using Math.ceil--Your result will be one day too large or in the spring if you use Math.floor you will be off by one day too few. Just use Math.round because 1 hour either way is not going to skew the result.

    function dateDiff(dateEarlier, dateLater) {
        var one_day=1000*60*60*24
        return (  Math.round((dateLater.getTime()-dateEarlier.getTime())/one_day)  );
    }
    
    0 讨论(0)
提交回复
热议问题