Formatting date and time in Google Chart

I am trying to utilize the Google Chart API to create a line chart. I need to retrieve data through an AJAX method and then set this data to the chart using a JavaScript JSON array. However, I am encountering difficulties with the datetime format within this process. Furthermore, the data obtained from AJAX is in string format that is generated from PHP. I am parsing this returned string into a JSON array which will be used as the chart data.

 v1 = '{"Date(2023, 1, 1, 20, 00, 00)", ... }'; # returned string from 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);

When attempting to use the

Date(year, month, day, hour, minute, second)
constructor (referencing theGoogle "Date String Representation" method) as the first element of the v1 array, I encounter the following error message in the console:
Unhandled Promise Rejection: Error: Type mismatch. Value Date(2023, 1, 1, 20, 00, 00) does not match type datetime in column index 0

What is the correct way to prepare datetime values in a JSON array for use with the Google Chart API?

Answer №1

In order for google's "Date String Representation" method to work effectively, the JSON format must be structured correctly when passing it to the data table constructor.

Check out the following snippet to see a working example:

The JSON data needs to adhere to a specific format, which is outlined below,
You can also find more information here: Format of the Constructor's JavaScript Literal data Parameter

It should be noted that there is a misleading example on their page where they unnecessarily use the new keyword before the date value.

Essentially, your JSON should have keys for rows and columns to ensure proper formatting...

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>

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

When using the JavaScript DataTable object literal notation to serialize data for creating your DataTable, avoid using the new Date() constructor. Instead, Google Charts offers a Date string representation that enables proper serialization and parsing of dates or datetimes during DataTable creation. This Date string format excludes the new keyword and encloses the expression in quotation marks:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggles with loading order in Knockout.JS

I've encountered an issue with loading my scripts properly for a page utilizing a knockout.js form. Upon page load, my viewmodel js file isn't immediately loaded, resulting in errors that cause the validation messages to flash and hidden divs to ...

Vue component lifecycle hook to fetch data from Firebase

Looking for a solution with Vue 2 component that utilizes Vuefire to connect declaratively with a Firebase real-time database: import { db } from '../firebase/db' export default { data: () => ({ cats: [] }), firebase: { ...

What's the best way to transform a dictionary into a unicode JSON string?

To me, it seems impossible to achieve this using the standard library's json module. The json.dumps method automatically escapes all non-ASCII characters and encodes the string to ASCII. Even if I try to prevent the escaping of non-ASCII characters, i ...

The easiest way to set Access-Control-Allow-Origin in ASP.Net MVC

Looking for a solution to access JSON data from ajax.example.com on someothersite.com? You might encounter the error message: Origin http://someothersite.com is not allowed by Access-Control-Allow-Origin. To overcome this, you can explore two options: ut ...

Create a specific website link for searching on YouTube

Is there a way to generate a YouTube URL using JavaScript or PHP that searches for videos on a specific user account and displays the best title match at the top of the search results? This is the code I am currently using: <!DOCTYPE html> <head ...

Employing jq to transfer the value of a child property to the parent dictionary

My TopoJSON file contains multiple geometries, structured as follows: { "type": "Topology", "objects": { "delegaciones": { "geometries": [ { "properties": { "name": "Tlalpan", "municip": "012", ...

Instructions for passing the chosen value to Django

I am struggling to set up a search button using Ajax and Django. I need to send the selected value to the server, but I can't seem to retrieve the value from the select HTML tag. The variable value always ends up empty ({"obj":""}). Any ideas? HTML : ...

Performing a PHP loop to concatenate the latest database entries

Imagine having a MySQL structure structured like this... +--------------+--------------------+-------------------+ | tdate | tuser | tvalue | +--------------+--------------------+-------------------+ | 11:16:48 | John ...

Feeling uncertain about how to utilize AJAX using the XMLHttpRequest object

The JavaScript function is: function loadData() { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { const data = xhttp.responseXML.documentElement.getElement ...

Service Worker's fetch event is not triggered upon registering the service worker

Service Worker is a new concept to me. As I delved into learning how to incorporate Service Worker into My Next.js Application, I encountered an issue with the fetch event handler. Oddly enough, the fetch event handler doesn't trigger upon initially r ...

Creating dynamic elements in JavaScript utilizing Bootstrap cards

Looking for help in integrating Bootstrap cards while dynamically generating elements using JavaScript? I am working on a project where I need to generate a list of restaurant recommendations based on user preferences entered through a form, utilizing the ...

Setting the button value to a textbox and refreshing the status information (Codeigniter)

How do I pass the value of my "ACTIVE" status attribute to my textbox? I want to update the user's status by clicking the ACTIVE button. The user's status is currently pending. While I can easily pass the userID, I'm facing an issu ...

Transform JSON into SOAP XML format using specific namespaces already provided

I have been tasked with the challenge of transforming a SOAP request into REST JSON and then converting the JSON back to SOAP XML. I have successfully converted SOAP to JSON using Serialize and XMlElement() classes. Now, the tricky part is converting JSON ...

Showing dummy data in demo mode with an AngularJS table

I stumbled upon this interesting jsfiddle http://jsfiddle.net/EnY74/20/ that seems to be using some demo data. If you check out this example https://jsfiddle.net/vsfsugkg/2/, you'll notice that the table originally has only one row, but I modified it ...

React Hook Form: When Submitting, Transform Date Object into String Date within an Array

Below is the data I am working with: { status: "Reserved", label: "Note", title: "Login Fragment - Navigation component With Coroutine", shareWith: "", notification_method: "Every Morning", notification_method_specific_time: Sat ...

How can you use Knex to order the results for each WHERE clause in a SELECT query?

When querying a database using knex, the desired results should be ordered in a specific manner. The current code provides the required results but lacks the expected order. knex("FRUITTBL") .select("FruitTag", "FruitName", ...

What is the process for customizing the default animation in the Dialog component?

Currently I am utilizing the Material UI framework and looking into modifying the default animation for a Dialog opening. Specifically, I would like the Dialog to appear from bottom to top when it opens up. Any suggestions on how this can be achieved? Ap ...

Changing text content of an element with dynamic formatting

When a link is clicked on, I want to dynamically set the text. Here is the current code: <a href="www.somelinkhere.com" onclick="getElementById('setText').innerHTML='text to replace'" target="someIFrame" ...

Constructor-generated element doesn't reflect changes upon component re-rendering

Why doesn't the <select> I create in the constructor update correctly when I select a different flavor? The other select and text update, but not this one. class ConstructorComponent extends React.Component { constructor() { super(); ...

What steps should I take to resolve the "You do not have authorization to access this directory or page" error in Azure App Services?

Currently, I am attempting to deploy my Next.js 13 application to AppServices using Github Actions. The compilation process on Github was successful, however, I am encountering an issue where my application does not seem to be deploying or starting up prop ...