Date difference in Javascript (ignoring time of day)

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

    I would also suggest having a look at the incredible moment.js library. It has a versatile diff function, which you can use to solve the above example as follows:

    function is_same_date(startDate, endDate) {
       var startMoment = moment(startDate).clone().startOf('day'),
           endMoment = moment(endDate).clone().startOf('day');
       return startMoment.diff(endMoment, 'days') == 0;
    }
    

    Here are some examples using moment.js diff:

    > d1 = new Date(2012,04,04,0,0)
    Fri May 04 2012 00:00:00 GMT-0400 (EDT)
    
    > d2 = new Date(2012,04,03,23,0)
    Thu May 03 2012 23:00:00 GMT-0400 (EDT)
    
    > d3 = new Date(2012,04,05,23,0)
    Sat May 05 2012 23:00:00 GMT-0400 (EDT)
    
    > moment(d2).diff(d1, 'days')
    0
    
    > moment(d1).diff(d2, 'days')
    0
    
    > moment(d1).diff(d3, 'days') // uh oh. this is why we use `startOf`
    -2
    
    > moment(d2).diff(d3, 'days')
    -2
    
    > moment(d3).startOf('day') // this modified d3, sets the time to 00:00:00.0000
    > d3
    Sat May 05 2012 00:00:00 GMT-0400 (EDT)
    

    If timezones are a concern, you can also use moment.utc() to convert to a normalized timezone.

提交回复
热议问题