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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 〇、前言 本文共108张图,流量党请慎重! 历时1个半月,我把自己学习Python基础知识的框架详细梳理了一遍。 ...
    Raxxie阅读 19,022评论 17 410
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,096评论 6 13
  • 第五章******************************************************...
    fastwe阅读 695评论 0 0
  • 与 TensorFlow 的初次相遇 https://jorditorres.org/wp-content/upl...
    布客飞龙阅读 3,956评论 2 89
  • 夜莺2517阅读 127,752评论 1 9