Date difference in Javascript (ignoring time of day)

前端 未结 15 2347
无人共我
无人共我 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: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)  );
    }
    

提交回复
热议问题