两个间隔时间时间段的计算与echartY轴值补0

240 阅读1分钟

应用场景是 ECharts 的X轴时间坐标计算和Y轴的数据落点,两个间隔时间时间段的计算,可以计算出两个时间相差的分别是什么并得到一个数组,获取后端数据映射到对应的时间轴上避免出现中间数据为空而导致的落点错误。

``` //默认已经引入momentJS
   
    function getDiffDayList(start, end, type) {

        let arryList = []
        const diff = end.diff(start, type);


        for (var i = 0; i < diff; i++) {
             //计算两个时间段相差的每小时时间间隔数组
            if (type == 'hour') {

                arryList.push(moment(start).add(i, 'hour').format('YYYY-MM-DD HH:mm:ss'))
            }

            //计算两个时间段相差的天间隔数组
            if (type == 'days') {

                arryList.push(moment(start).add(i, 'day').format('YYYY-MM-DD HH:mm:ss'))
            }

              //计算两个时间段相差的月间隔数组
            if (type == 'months') {

                arryList.push(moment(start).add(i, 'month').format('YYYY-MM-DD HH:mm:ss'))
            }
             //计算两个时间段相差的年间隔数组

            if (type == 'years') {

                arryList.push(moment(start).add(i, 'year').format('YYYY-MM-DD HH:mm:ss'))
            }



        }


      //返回计算出的间隔时间数组

        return arryList


    }
    //获取时间间隔
    const xAxisTime=getDiffDayList('2022-09-27 00:00:00' ,'2022-09-28 00:00:00','hour')
    
    //填充新数组数据
     const  dataArrays=new Array(xAxisTime.length).fill('')
     //获取后台返回数据
     const dataValue=[{id:"1",value:"100",updataTime:"2022-09-27 10:00:00"}]//这里用个假数据
     //把数据落点到对应的新数组上
     dataValue.forEach((item,index)=>{

  
        dataArrays[xAxisTime.indexOf(item.updateTime)]=item.value 
   })
   //...去绘制eharts图标