How to format x-axis based on how long between start and end time datepicker of data in chart.js?

自闭症网瘾萝莉.ら 提交于 2020-06-01 05:08:18

问题


Hello I am new to javascript. I have chart.js with the data from API look like this :

  .....//datepicker code......

  $.ajax({
  method: "GET",
  url: endpoint,
  data: {
  startDate: startDate,
  endDate: endDate
  },
  success: function(data){
  //get data by fields
  var accelero_x = [], timestamp = [];
  for (var i=0; i<data.length; i++){
  accelero_x.push(data[i].accelero_x);
  timestamp.push(data[i].timestamp);
  }
  //plot the chart
  var ctx = document.getElementById("accelero_xChart").getContext('2d');
  var accelero_xChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: timestamp,
        datasets: [{
            label: 'accelero-x (mV/g)',
            data: accelero_x,
            backgroundColor: [
                '#ff000000'
            ],
            borderColor: [
            '#331698'
            ],
            pointBackgroundColor: '#331698',
            borderCapStyle: 'round',
            borderWidth: 3
        }]
    },
    options: {
        reponsive: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:false,
                    stepSize:0.1
                },
                  scaleLabel: {
                  display:     true,
                  labelString: 'accelero-x (mV/g)'
              }
            }],
            xAxes: [{

                    display: true,
                    type: "time",
                    time: {
                          min: moment(startDate).toDate(),//Date object type
                          max: moment(endDate).toDate()//Date object type
                    },
                  scaleLabel: {
                  display:     true,
                  labelString: 'Time (hour)'
              }
            }]
        }
    }
  });
  },
  error: function(error_data){
  console.log(error_data)
  } 

  });

My chart right now displaying the x-Axes per 2 hours. But I want different formats based on how long between the startDate and endDate time of data in the graph from the datepicker. If I choose more than two days between the startDate and endDate from datepicker, I want set format to show just date, not hours.

For example, when I choose the date from 7 May until 8 May, the x-Axes will be formatted into per 2 hours (HH:MM example: 01:00, 03:00, 05:00, and so on). But when I choose the date from 7 May until 9 May, the x-Axes will be formatted into date (ex: 7 May, 8 May, 9 May). How can I do that?

来源:https://stackoverflow.com/questions/62086503/how-to-format-x-axis-based-on-how-long-between-start-and-end-time-datepicker-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!