问题
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