format dates for chart - Javascript Chart.js

Javascript examples for Chart.js:Chart Date Date

Description

format dates for chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>ChartJS Line Chart</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  ww  w .j  ava  2s  .c  o m*/
var ctx = document.getElementById('chartJSContainer').getContext('2d');
var timeFormat = 'MM/DD/YYYY HH:mm';
var json = '[{"ReportDate":"2018-01-31T00:00:00.000Z","YtD":14609547.9130000044},{"ReportDate":"2018-02-09T00:00:00.000Z","YtD":-7823612.5760000022},{"ReportDate":"2018-02-12T00:00:00.000Z","YtD":-8326611.3190000039},{"ReportDate":"2018-02-13T00:00:00.000Z","YtD":-9144531.6940000001},{"ReportDate":"2018-02-14T00:00:00.000Z","YtD":-8122732.6769999973}]';
var json_obj = JSON.parse(json);
var itemCount = json_obj.length;
var dateLabels = [];
var pnlData = [];
for (var i = 0; i < itemCount; i++){
  var d = moment(json_obj[i].ReportDate);
  dateLabels.push(d);
  pnlData.push(json_obj[i].YtD);
}
var config = {
  type: 'line',
  data: {
    labels:  dateLabels,
    datasets:[
      {
        label: 'YtD',
        data: pnlData
      }
    ]
  },
  options:{
    title: {
      display: true,
      text: 'Year to Date PnL'
    },
    legend: {
      display: false,
      position: 'right'
    },
    scales: {
      xAxes: [
        {
          type: 'time',
          time: {
            displayFormats: {
              day: 'MMM D'
            }
          }
        }
      ]
    }
  }
};
new Chart(ctx, config);
    }

      </script> 
   </head> 
   <body>  
      <canvas id="chartJSContainer" width="600" height="400"></canvas>   
   </body>
</html>

Related Tutorials