Home > Back-end >  DateTime format in Google Chart
DateTime format in Google Chart

Time:02-05

I want to create a line chart by Google Chart API. I want to get data from AJAX method and set data to chart as javascript JSON array, but I have a problem with datetime format inside. Additional, a AJAX data is a string which generated from PHP. I parse returned string to JSON array which I want to set as chart data.

 v1 = '{"Date(2023, 1, 1, 20, 00, 00)", ... }'; # returned string AJAX
 v1 = jQuery.parseJSON(v1);

 data = new google.visualization.DataTable();
 data.addColumn('datetime', 'Time');
 data.addColumn({...something else...});
 data.addRows(v1);

 options = { ... };
 chart = new google.visualization.LineChart(document.getElementById('linechart_material'));
 chart.draw(data, options);

And I have this error message in console, when I try use Date(year, month, day, hour, minute, second) constructor (Google "Date String Representation" method) as first element of v1 array: Unhandled Promise Rejection: Error: Type mismatch. Value Date(2023, 1, 1, 20, 00, 00) does not match type datetime in column index 0

How to prepare datetime in JSON array and Google Chart API?

CodePudding user response:

google's "Date String Representation" method only works when you are passing the json to the data table's constructor.

see following working snippet.

the json must be in a specific format, which you can see below,
or here: Format of the Constructor's JavaScript Literal data Parameter

however, they use a bad example on their page because they use the new keyword in front of the date value, which isn't required.

point being, you must have the json formatted as below, with keys for rows and columns...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {

  var jsonData = {
      "cols": [
        {"label": "datetime", "type": "date"},
        {"label": "value", "type": "number"}
      ],
      "rows": [
        {"c":[{"v": "Date(2023, 1, 1, 0, 0, 0)"}, {"v": 1}]},  // = Feb 1, 2023 (month number index is zero-based)
        {"c":[{"v": "Date(2023, 1, 2, 0, 0, 0)"}, {"v": 2}]},
        {"c":[{"v": "Date(2023, 1, 3, 0, 0, 0)"}, {"v": 3}]},
      ]
  };
  
  var dataTable = new google.visualization.DataTable(jsonData);
  
  console.log('data table rows', dataTable.getNumberOfRows());  
  console.log('row 1 date', dataTable.getValue(0, 0));  
});
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

from here: https://developers.google.com/chart/interactive/docs/datesandtimes#dates-and-times-using-the-date-string-representation

When serializing data using the JavaScript DataTable object literal notation to build your DataTable, the new Date() constructor cannot be used. Instead, Google Charts provides a Date string representation that allows your date or datetime to be serialized and parsed properly when creating a DataTable. This Date string format simply drops the new keyword and wraps the remaining expression in quotation marks:

"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"

  • Related