拆线图按年、按月,按天统计,前端传时间只要起始时间与结束时间

工具类

package test.common.utils;
import test.EventInfoCountVo;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StatisticalUtil {

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1 时间参数 1 格式:1990-01-01 12:00:00
     * @param str2 时间参数 2 格式:2009-01-01 12:00:00
     * @return String 返回值为:xx天xx小时xx分xx秒
     */
    public static Long getDistanceTime(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return day;
    }

    /**
     * 获取现在时间
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    //构造横轴数据,按12月与天
    public static void  completion(List<EventInfoCountVo> data, int size){
        if(data.size()<size){
            int [] s = new int[size];
            for (EventInfoCountVo datum : data) {
                s[datum.getColumn()-1]=1;
            }
            for (int i =0 ;i< s.length;i++) {
                if(s[i]==0){
                    EventInfoCountVo eventInfoCountVo = new EventInfoCountVo();
                    eventInfoCountVo.setColumn(i+1);
                    eventInfoCountVo.setCount(0);
                    data.add(eventInfoCountVo);
                }
            }
        }

    }

    //按年份
    public static void  completionByYear(List<EventInfoCountVo> data, int size,Integer startTime, Integer endTime){

        endTime = endTime + 1;

        //相差的年份 2017 2019
        for(int i=startTime; i<endTime; i++){

            //2019
            int [] s = new int[endTime];

            //2018,2019
            for(int j=0; j<data.size(); j++){
                s[data.get(j).getColumn()]=1;
            }

            if(s[i]==0){
                EventInfoCountVo eventInfoCountVo = new EventInfoCountVo();
                eventInfoCountVo.setColumn(i);
                eventInfoCountVo.setCount(0);
                data.add(eventInfoCountVo);
            }

        }

    }

    public static Map<String ,String> getYearOrMonthOrDay(String startTime, String endTime){
        Integer size = 0;
        Integer startIndex = 0;
        Integer endIndex = 0;

        if(startTime != null && !startTime .equals("")  && endTime != null && !endTime .equals("")){

            Long distanceTime = getDistanceTime(startTime, endTime);
            if((!startTime.substring(0,4).equals(endTime.substring(0,4))) || distanceTime > 366L){
                //年差
                //Integer yearPoor = Integer.valueOf(endTime.substring(0,4)) - Integer.valueOf(startTime.substring(0,4));
                //System.out.println("年差是多少="+yearPoor);

                //按年
                startTime = startTime.substring(0,4)+"-01-01 00:00:00";
                endTime = endTime.substring(0,4)+"-12-31 23:59:59";
                startIndex = 1;
                endIndex = 4;
                //size = yearPoor;

            }else if((31L <= distanceTime) && (distanceTime<= 366L)){
                //当年当月 2019-11-12 59:59:59
                startTime = startTime.substring(0,7)+"-01 00:00:00";
                endTime = endTime.substring(0,7)+"-31 23:59:59";
                startIndex = 6;
                endIndex = 2;
                size = 12;

            }else if(distanceTime < 31L){
                //按天
                startTime = startTime.substring(0,7)+"-01 00:00:00";
                endTime = startTime.substring(0,7)+"-31 23:59:59";
                startIndex = 9;
                endIndex = 2;
                size = 30;

            }

        }else{
            //默认当年月份
            startTime = (Integer.valueOf(getStringDate().substring(0,4))-1)+"-01-01 00:00:00";
            endTime = getStringDate().substring(0,4)+"-12-31 23:59:59";
            //startIndex = 6;
            //endIndex = 2;
            //size = 12;
            startIndex = 1;
            endIndex = 4;
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("startTime",startTime);
        map.put("endTime",endTime);
        map.put("startIndex",startIndex+"");
        map.put("endIndex",endIndex+"");
        map.put("size",size+"");

        return map;

    }
}

返回结果的集

import lombok.Data;

@Data
public class EventInfoCountVo {
    private Integer column;
    private Integer count;
}

//调用,实现类

@Override
    public List<EventInfoCountVo> statisticsByTime(Long townId, Integer flagType, Long platformTypeId,
                                                   String startTime, String endTime, List<Long> platformIds) {
     //通过工具类方法getYearOrMonthOrDay,获取到具体时间startTime、endTime与年月天标志size     //年:2019-01-01 00:00:00 到 2020-01-01 23:59:59     //月:2019-10-01 00:00:00 到 2019-10-31 23:59:59     //天
        Map<String, String> yearOrMonthOrDayMap = StatisticalUtil.getYearOrMonthOrDay(startTime, endTime);
        startTime = yearOrMonthOrDayMap.get("startTime");
        endTime = yearOrMonthOrDayMap.get("endTime");
        Integer startIndex = Integer.valueOf(yearOrMonthOrDayMap.get("startIndex"));
        Integer endIndex = Integer.valueOf(yearOrMonthOrDayMap.get("endIndex"));
        Integer size = Integer.valueOf(yearOrMonthOrDayMap.get("size"));
     //返回的数据
        List<EventInfoCountVo> eventInfoCountVos = baseMapper.statisticsByTime(startTime, endTime,startIndex, endIndex);

        if(startIndex != 1){        //构造横轴数据
            StatisticalUtil.completion(eventInfoCountVos,size);
        }else{
            Integer yearPoor = Integer.valueOf(endTime.substring(0,4)) - Integer.valueOf(startTime.substring(0,4));
            System.out.println("年差是多少="+yearPoor);
            StatisticalUtil.completionByYear(eventInfoCountVos,yearPoor,Integer.valueOf(startTime.substring(0,4)),Integer.valueOf(endTime.substring(0,4)));
        }

        return eventInfoCountVos;
    }

xml层

<!--风险管控之智能发现—学校小区统计分析—按按年、月、按天统计工单-->
    <select id="statisticsByTime" resultType="cn.sinvie.modules.event.entity.EventInfoCountVo">
        SELECT SUBSTRING(ei.gmt_create,#{startIndex},#{endIndex}) AS `column` ,COUNT(*) `count`
        FROM `event_info` as ei
        WHERE ei.is_deleted = 0
        <if test="startTime != null and startTime != ‘‘ and endTime != null and endTime != ‘‘">
            AND
            STR_TO_DATE(ei.gmt_create,‘%Y-%c-%d %H:%i:%s‘)
            BETWEEN
            #{startTime}
            AND
            #{endTime}
        </if>
        GROUP BY `column`
    </select>

//前端代码,其中200,300是用来区别年月日的,或者让后端返回

//初始化拆线图数据、按年月日统计,初始化数据
    initLineData() {
      var x = [];
      var y = [];

      this.$http({
        url: this.$http.adornUrl("/statistic/statisticsByTime"),
        method: "get",
        params: this.$http.adornParams({
          startAt: this.startTime,
          endAt: this.endTime,
        })
      }).then(res => {
        console.log("按年月日统计,初始化数据", res);

        if(res.data.data != null && res.data.data.length > 0){

          if( res.data.data[0].column <200 && res.data.data.length === 12){
            //月
            var i = 1;
            for (let j = 0; j < res.data.data.length; j++) {
              res.data.data.forEach(item => {
                if (item.column === i) {
                  x.push(item.column+"月")
                  y.push(item.count);
                  ++i;
                }
              });
            }

            this.$nextTick(() => {
              this.initLineChart(x,y);
            });

          }else if(res.data.data[0].column <200 && res.data.data.length === 30){
            //天
            var i = 1;
            for (let j = 0; j < res.data.data.length; j++) {
              res.data.data.forEach(item => {
                if (item.column === i) {
                  x.push(item.column+"号")
                  y.push(item.count);
                  ++i;
                }
              });
            }

            this.$nextTick(() => {
              this.initLineChart(x,y);
            });

          }else if(res.data.data[0].column > 300){
            //年
            for (let j = 0; j < res.data.data.length; j++) {
              x.push(res.data.data[j].column);
              y.push(res.data.data[j].count);

            }

            this.$nextTick(() => {
              this.initLineChart(x,y);
            });

          }
        }

      });
    },

    //初始化拆线图echart
    initLineChart(x,y) {
      this.chart = echarts.init(this.$refs.schoolLinePeriod, "macarons");

      this.chart.setOption({
        color: [‘#3398DB‘],

        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985"
            }
          }
        },
        grid: {
          left: "1%",
          right: "5%",
          top: "25%",
          bottom: "10%",
          containLabel: true
        },
        xAxis: [
          {
            //name: "月份",
            type: "category",
            boundaryGap: false,
            data: x
          }
        ],
        yAxis: [
          {
            type: "value",
            //name: "隐患数量"
          }
        ],
        series: [
          {
            name: "隐患数量",
            type: "line",
            stack: "总量",
            label: {
              normal: {
                show: true,
                position: "top"
              }
            },
            areaStyle: { normal: {} },
            data: y
          }
        ]
      });
    },

实现效果,分别是年、月、天

原文地址:https://www.cnblogs.com/caohanren/p/12213017.html

时间: 2024-11-06 03:35:31

拆线图按年、按月,按天统计,前端传时间只要起始时间与结束时间的相关文章

手机CPU天梯图2018年5月最新版

话不多说,以下是2018年5月最新的手机CPU天梯图精简版,由于最近一两个月,芯片厂商发布的新Soc并不不多,因此这次天梯图更新,主要是来看看今年主流手机厂商都流行使用哪些处理器. 手机CPU天梯图2018年5月最新版(精简版) 高端CPU 高通 联发科 苹果 华为 三星 小米       麒麟980         A10X Fusion       骁龙845   苹果A11   Exynos 9810                                       骁龙835

ORACLE取周、月、季、年的开始时间和结束时间

 1           取周的开始时间和结束时间 取周的开始时间,以星期一为开始. SQL>SELECT TRUNC(TO_DATE('2013-11-25 10:31:11','YYYY-MM-DD HH24:MI:SS'),'D') + 1 ASA FROM DUAL; A ----------- 2013/11/25 取周的结束时间,以星期日为结束 SQL>SELECT TRUNC(TO_DATE('2013-11-25 10:31:11','YYYY-MM-DD HH24:MI:

ORACLE取周、月、季、年的開始时间和结束时间

 1           取周的開始时间和结束时间 取周的開始时间.以星期一为開始. SQL>SELECT TRUNC(TO_DATE('2013-11-25 10:31:11','YYYY-MM-DD HH24:MI:SS'),'D') + 1 ASA FROM DUAL; A ----------- 2013/11/25 取周的结束时间.以星期日为结束 SQL>SELECT TRUNC(TO_DATE('2013-11-25 10:31:11','YYYY-MM-DD HH24:MI:

MySql按周/月/日分组统计数据的方法

知识关键词:DATE_FORMAT select DATE_FORMAT(create_time,'%Y%u') weeks,count(caseid) count from tc_case group by weeks; select DATE_FORMAT(create_time,'%Y%m%d') days,count(caseid) count from tc_case group by days; select DATE_FORMAT(create_time,'%Y%m') month

sql语句分别按日,按周,按月,按季统计金额

如: 表:consume_record 字段:consume (money类型) date (datetime类型) 请问怎么写四条sql语句分别按日,按周,按月,按季统计消费总量. 如:1月 1200元 2月 3400元 3月 2800元 --按日 select sum(consume),day([date]) from consume_record where year([date]) = '2006' group by day([date]) --按周quarter select sum(

C#中周,月,第几周,周开始结束时间de方法总结

1.c#获取当前时间是本年的第几周,本月的第几周 private static int getWeekNumInMonth(DateTime daytime) { int dayInMonth = daytime.Day; //本月第一天 DateTime firstDay = daytime.AddDays(1 - daytime.Day); //本月第一天是周几 int weekday = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.Da

php获取上一个月的开始与结束时间遇到的问题

改正之前: $_lastMonthStart = date('Y-m-1 00:00:00', strtotime("-1 month")); $_lastMonthEnd = date('Y-m-d H:i:s', strtotime('-1 sec', strtotime($_monthStart))); $preMonthRange = [$_lastMonthStart, $_lastMonthEnd]; 想要的结果:上一个月的开始和结束时间这一范围. 出现的问题描述:5月31

java获取当前时间的年周月季度等的开始结束时间

import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by xiaochun on 2016/3/24. */ public class TimeUtil { public static void main(String[] args) { System.out.println("当前小时开始:"+getCurrentHourStartTime

Ext 拆线图 LiveAnimated

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />     <meta http-equiv="X-