js两个时间相减

在开发中,需要处理一些时间之间的差值,后端传给我们开始时间与结束时间,我们则需要用当前时间来判断两组时间之间的差值,在js中可以这样写,上代码:

    let now = new Date()
    let year = now.getFullYear()
    let month = now.getMonth()
    let date = now.getDate()
    let hour = now.getHours()
    let minu = now.getMinutes();
    let sec = now.getSeconds()
    month = month + 1
    if (month < 10){ month = "0" + month;}
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    let time = year + '-' + month + '-' + date + ' ' + hour + ':' + minu + ':' + sec

    Date.prototype.diff = function(date){
        return (this.getTime() - date.getTime())/(24 * 60 * 60 * 1000)
     }

     let nowTime = new Date(now)
     let end = new Date('2021/03/26 12:43:45')
     let endTime = end.diff(nowTime)

如果想要向下取整可以这样写:

  let floorTime = Math.floor(endTime)

如果想要向上取整可以这样写:

  let ceilTime = Math.ceil(endTime)

你可能感兴趣的:(js两个时间相减)