美文网首页
JS 计算两个时间戳相差年月日时分秒

JS 计算两个时间戳相差年月日时分秒

作者: 昊_f343 | 来源:发表于2021-08-16 21:06 被阅读0次

    // 计算两个时间戳相差的多少年多少月多少天

    calculateDiffTime() {

      let startTime = '1629107469000'  //2021-08-16 17:51

      let endTime = '1976262719000'  //2032-08-16 17:51

      let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2];

      let start = new Date(startTime);

      let end = new Date(endTime);

      let year = end.getFullYear() - start.getFullYear();

      let month = end.getMonth() - start.getMonth();

      let day = end.getDate() - start.getDate();

      if (month < 0) {

        year--;

        month = end.getMonth() + (12 - start.getMonth());

      }

      if (day < 0) {

        month--;

        let index = flag.findIndex((temp) => {

          return temp === start.getMonth() + 1

        });

        let monthLength;

        if (index <= 6) {

          monthLength = 31;

        } else if (index > 6 && index <= 10) {

          monthLength = 30;

        } else {

          monthLength = 28;

        }

        day = end.getDate() + (monthLength - start.getDate());

      }

      this.result = `相差${year}年${month}月${day}天`;

      console.log(this.result)

    }

    #  计算两个时间戳相差的多少年多少月多少天多少小时多少分多少秒(另一种写法)

    //计算两个时间戳相差的多少年多少月多少天多少小时多少分多少秒

    calculateDiffTime (){

      let startTime = '1629107469000'  //2021-08-16 17:51

      let endTime = '1976262719000'  //2032-08-16 17:51

      let runTime = parseInt((endTime - startTime) / 1000);

      var year = Math.floor(runTime / 86400 / 365);

      runTime = runTime % (86400 * 365);

      var month = Math.floor(runTime / 86400 / 30);

      runTime = runTime % (86400 * 30);

      var day = Math.floor(runTime / 86400);

      runTime = runTime % 86400;

      var hour = Math.floor(runTime / 3600);

      runTime = runTime % 3600;

      var minute = Math.floor(runTime / 60);

      runTime = runTime % 60;

      var second = runTime;

      console.log(`相差${year}年${month}月${day}天${hour}小时${minute}分${second}秒`);

     return year+','+month+','+day+','+hour+','+minute+','+second;

    }

    相关文章

      网友评论

          本文标题:JS 计算两个时间戳相差年月日时分秒

          本文链接:https://www.haomeiwen.com/subject/rwyvbltx.html