Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data.

Here is my initial code snippet:

var container = document.getElementById('divChart1');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();

dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'string', id: 'Category' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });

My current challenge lies in populating the chart through AJAX, particularly with the Date types causing issues.

The data rows should be populated as follows:

dataTable.addRows([
  ['Aaa', 'A', new Date(2014, 1, 1), new Date(2016, 12, 31)],
  ['Bbb', 'B', new Date(2014, 1, 1), new Date(2016, 5, 31)]]);

Is there a way to return a serialized collection from my AJAX service and parse it directly, or do I need to iterate through the collection and create a new JavaScript Date each time?

Attempting

dataTable.addRows(JSON.parse(result.chartData));
results in the error:
Error: Type mismatch. Value 2015-08-26T11:59:23.889004+02:00 does not match type date in column index 2

For reference, here's how the AJAX service appears:

List<List<object>> chartData = new List<List<object>>();

chartData.Add(new List<object>() { 
    "Aaa",
    "A",
    DateTime.Now,
    DateTime.Now.AddMonths(3)
});

return JsonConvert.SerializeObject(chartData);

edit: After some tweaking, this is what worked for me:

chartData.Add(new List<object>() { 
    "Aaa",
    "A",
    DateTime.Now.Year + "#" + DateTime.Now.Month + "#" + DateTime.Now.Day,
    DateTime.Now.AddMonths(3).Year + "#" + DateTime.Now.AddMonths(3).Month + "#" + DateTime.Now.AddMonths(3).Day
});

var result = $.parseJSON(result.chartData);
$.each(result, function (k, v) {
    var s = v[2].split('#');
    var e = v[3].split('#');
    dataTable.addRow([v[0], v[1], new Date(s[0], s[1], s[2]), new Date(e[0], e[1], e[2])]);
});

This workaround is not intended as the official answer since it doesn't fully address the original question.

Answer №1

Update

After creating the JSON as per your request, it seems that using

JSON.parse('new Date(2014, 1, 1)')
does not work because JavaScript date constructors are not considered valid JSON according to official standards.

Therefore, it is recommended to serialize your DateTime object as a string and provide a reviver function to the JSON.parse() method to handle date string recognition and conversion to a JavaScript Date object. Here's an example:

Original Answer

If you need to write and read dates in the format

new Date(2014, 1, 1 [, H [, M [, S [, MS]]]])
, you can extend the JavaScriptDateTimeConverter following this example from Stack Overflow:

public class JavaScriptYMDDateTimeConverter : JavaScriptDateTimeConverter
{
    // Implementation details here...
}

You can then utilize this custom converter like so:

var settings = new JsonSerializerSettings { Converters = new JsonConverter[] { new JavaScriptYMDDateTimeConverter { StripTimeOfDay = true } } }; 
return JsonConvert.SerializeObject(chartData, settings);

This will result in an output similar to:

[["Aaa","A",new Date(2015,7,26),new Date(2015,10,26)]]

Answer №2

To format the dates, you can enclose them in brackets.

For example:

{
      "cols": [
            {"label": "Date", "type": "date"},
            {"label": "Serie 1", "type": "number"},
            {"label": "Serie 2", "type": "number"},
      ],
      "rows": [
            {"c":[{"v": "Date(2014, 1, 1)"}, {"v": 1000}, {"v": 400}]},
            {"c":[{"v": "Date(2014, 2, 25)"}, {"v": 1170}, {"v": 460}]},
            {"c":[{"v": "Date(2014, 3, 15)"}, {"v": 660}, {"v": 1120}]},
            {"c":[{"v": "Date(2014, 4, 30)"}, {"v": 1030}, {"v": 540}]},
      ]
}

Please take into consideration Google's recommendations regarding the Date constructor and compatibility with different browsers: https://developers.google.com/chart/interactive/docs/datesandtimes

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

Incorporating CSS Styles in EJS

Struggling with connecting my CSS files while using EJS. I've checked out another solution but still can't seem to get it right. Here is the code I used as a reference for my CSS file. EJS <html> <head> <meta charset="utf-8 ...

Separating Angular JS controller and Factory into individual files allows for easier organization and

As someone new to web development and Angular, I recently created a module, factory, and controller all in the same file (app.js). Below is an example of the code: //Main Module var ipCharts = angular.module('ipCharts', []); //Factory ipCharts. ...

What could be causing the pause function for videos to stop working in Chrome?

Recently, I've encountered an issue with the pause() function in Chrome while trying to stop a video playback. Despite using this method successfully in the past with Firefox, it seems to no longer work on Chrome browsers. I've simplified my code ...

Encountering a 403 error message when trying to access the URL

I am facing an issue while trying to fetch JSON data from an API URL. I keep receiving the error message java.io.IOException: Server returned HTTP response code: 403. Interestingly, if I directly paste the link into my browser, it works perfectly fine. He ...

Navigate through content easily using the arrow keys on your keyboard with the help of Easy Slider

I'm attempting to modify the Easy Slider in order to enable navigation of the slideshow with the arrow keys on the keyboard. I made adjustments to the javascript's animate function, changing it from: default: t = dir; break; ...to: default: t ...

What is the process of serializing a JBox2d World object?

My server has multiple clients connecting, each controlling a player body. Collisions can occur, so players need to see other bodies to understand movement restrictions. To achieve this, I transmit the "World" object using object streams and parse and dra ...

The issue of fonts module resolution in React-Native remains unsolved

I am embarking on a basic build project using 'create-react-native-app' and yarn as the package manager. My main goal is to incorporate 'native-base' for enhancing the user interface. So far, the only addition to my app.js file is a B ...

Result being returned from XMLHTTPRequest function

I've been experimenting with an XMLHttpRequest and managed to get the basic code functioning properly. However, I'm struggling to create a function that will return a boolean variable indicating whether it has worked or not: var xhr = new XMLHtt ...

Bring in numerous json documents from a folder and linking the information

Currently, my task involves reading multiple JSON files from a specified directory in order to convert them into a dataset. Within the 'json' directory, there exist files named text1, text2, and text3. Below is the code snippet that I have create ...

Unexpected redirection to a different page after submitting Django Ajax Form

Whenever I submit a comment form using ajax in Django, the page redirects to a blank page displaying the success data: {"status":"success", "msg":"Comment added successfully"} , instead of staying on the current page. I would like the page to remain on t ...

Delaying Ajax request

I've encountered some strange behavior. After the initial ajax call triggered by selecting a city from a dropdown menu, I then have a continuous ajax call on a delay. The first call stores the selected city value in a global variable. $('.sele ...

Does catching errors cause the for loop to stop in JavaScript?

for (let index = 0, total = IDs.length; index < total; index++) { item = IDs[index]; hasError = false; try{ let id = db.getSiblingDB("door").jhi_user.findOne({"_id" : item}); } catch (error){ failedIDs.push(item); ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

Creating a Website Optimized for Mobile Devices

As a beginner web developer, I am in the process of creating a mobile-friendly website system. Currently, I am utilizing Bootstrap for responsiveness, PHP5, MySQL, and occasionally Ajax/JQuery. Recently, I came across JQuery Mobile. While I have been usin ...

Move on to a different screen in a React Component once the data has been fetched

Currently, I am delving into the world of React and TypeScript and attempting to utilize "react-router-dom" in order to create a login component that will interact with my backend server. Essentially, my goal is to develop a "Login" class that, upon form ...

The combination of Google API, PHP, and Ajax Call has resulted in the presence of the 'Access-Control-Allow-Origin' header on the requested resource

When attempting to access my calendar entries via OAuth using the Google API on a local Raspberry Pi server, I encountered the following error: Failed to load ****-****.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fopenhabianpi..%2Fsmarthome% ...

Watching a specific property amongst various objects using VueJS deep watcher

Issue at Hand In my scenario, I have an array named "products" that consists of multiple objects. Each object within the product array includes a property called "price". My goal is to monitor any changes in this particular property for each product. This ...

Creating unique styles for components based on props in styled MUI: A comprehensive guide

One challenge I am facing is customizing the appearance of my component based on props, such as the "variant" prop using the 'styled' function. Here is an example code snippet: import { styled } from '@mui/material/styles'; const Remov ...

Animate the div only when the button is clicked

I need a way to hide the text inside a div when it exceeds a certain height, but then expand it to full height upon clicking a button. However, I want this action to only affect the parent div of that specific button, rather than all the divs on the page. ...

How can Request.UrlReferrer be configured using client-side JavaScript? If it can be done, what is the process?

In my application, I heavily rely on Request.UrlReferrer to handle link clicks and maintain a page history for users. Due to new requirements, I now need to navigate to a specific location using <input type="button" /> instead of <a href="mypage. ...