首页 > 解决方案 > 根据在类型周的输入中选择的周更改标签天

问题描述

我正在尝试使用 Chart.js 更改标签的日期,但它向我显示了输入类型周中所选周的日期,我拥有的代码如下:

<div class="card-body">
        <input class="form-control" type="week" value="2021-W32" id="example-week-input">
        <canvas id="myChart1"></canvas>
      </div>

下面我留下执行的 javascript 代码。

var ctx1 = document.getElementById('myChart1').getContext('2d');
var chart = new Chart(ctx1, {
    type: 'line',
    data: {
        labels: ['09/08/2021', '10/08/2021', '11/08/2021', '12/08/2021', '13/08/2021', '14/08/2021', '15/08/2021'],
        datasets: [{
            label: 'Ventas Dirias Sitio Web',
            backgroundColor: 'rgb(228, 0, 43)',
            borderColor: 'rgb(228, 0, 43)', 
            data: [0, 0, 0, 0, 0, 0, 0]
        }       
        ]},
    options: {}
});

我将非常感谢您的帮助。

标签: javascripthtml

解决方案


您可以使用以下方式处理一周的渲染:

// function to get first day of the week
function FirstDayOfWeek(w, y) {
  let date = new Date(y, 0, (1 + (w) * 7)); 
  date.setDate(date.getDate() + (1 - date.getDay())); // 0 - Sunday, 1 - Monday etc
  return date
}

// function to format the date to dd/MM/yyyy
function FormatDate(d)
{
  var dd = d.getDate();
  var mm = d.getMonth() + 1;

  var yyyy = d.getFullYear();
  if (dd < 10) {
      dd = '0' + dd;
  }
  if (mm < 10) {
      mm = '0' + mm;
  }
  return dd + '/' + mm + '/' + yyyy;
}

function RenderChart() {
  let week = document.getElementById("example-week-input").value
  let year = week.split("-")[0]*1,
    weekNumber = week.split("-")[1].substring(1)*1; // to skip the W

  let currentDay = FirstDayOfWeek(weekNumber, year); // get the first day of the week
  
  let chartLabels = [];
  for (let i = 0; i < 7; i++)
  {
    chartLabels.push(FormatDate(currentDay));
    currentDay.setDate(currentDay.getDate() + 1); // move to next day
  }

  // render chart with the new days label
  var ctx1 = document.getElementById('myChart1').getContext('2d');
  var chart = new Chart(ctx1, {
      type: 'line',
      data: {
          labels: chartLabels,
          datasets: [{
              label: 'Ventas Dirias Sitio Web',
              backgroundColor: 'rgb(228, 0, 43)',
              borderColor: 'rgb(228, 0, 43)', 
              data: [0, 0, 0, 0, 0, 0, 0]
          }       
          ]},
      options: {}
  });
}

然后你只需要修改你的星期选择器,在“onchange”事件中添加对“RenderChart()”的调用。您还可以在页面加载时调用该函数以自动呈现选定的星期。

<input class="form-control" type="week" value="2021-W32" id="example-week-input" onchange="RenderChart()">

推荐阅读