Date difference in Javascript (ignoring time of day)

前端 未结 15 2364
无人共我
无人共我 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:09

    I just had this problem and solved it after finding this question, so I came back to post this. This will get the total days regardless of time. And DST doesn't mess it up:

    date1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
    date2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
    var ms = Math.abs(date1-date2);
    return Math.floor(ms/1000/60/60/24); //floor should be unnecessary, but just in case
    

    The trick is converting to a UTC date that doesn't even know about the times of the original dates.

提交回复
热议问题