Google Charts: passing dates without using date ()?

Summary

I am trying to make a line graph in google graphs with dates in the form of the X axis. I have everything sorted, but this requires the transmission dates to be Date objects, i.e. new Date(2005, 3, 13) . Is there a way to pass it as a Unix timestamp or possibly a string?

More details

So, I have a bunch of data in PHP that I want to use for plotting. I take the data and place it in an array in a format that will produce the correct JSON format when passing through json_encode() , for Google data documents :

 $graph_data = array( 'cols' => array( array( 'id' => 'date', 'label' => 'Date', 'type' => 'datetime', ), array( 'id' => 'odometer', 'label' => 'Miles', 'type' => 'number', ), ), 'rows' => array( array( 'c' => array( array( 'v' => 1331479502 ), array( 'v' => 56872 ), ), ), array( 'c' => array( array( 'v' => 1331375984 ), array( 'v' => 55324 ), ), ), array( 'c' => array( array( 'v' => 1328966460 ), array( 'v' => 54244 ), ), ), ), ); 

{"cols":[{"id":"date","label":"Date","type":"datetime"},{"id":"odometer","label":"Miles","type":"number"}],"rows":[{"c":[{"v":1331479502},{"v":56872}]},{"c":[{"v":1331375984},{"v":55324}]},{"c":[{"v":1328966460},{"v":54244}]}]}

So, I have JSON creation, but the API wants dates to be passed as a Date object, not a number (or a string). It gives an error right now, but if I change it from datetime to number , it draws fine, so I know that my JSON format is correct.

Is there anything I can do to make the API accept Unix timestamps or maybe some string?

As I typed this, I realized that maybe I could use Javascript to go to the JSON object and replace the timestamps with Date objects, but it would be nice if I didn't have to manipulate the data through Javascript.

EDIT

I got part of the path by setting type to number and skipping dates as follows:

  array( 'c' => array( array( 'v' => 1331479502, 'f' => 'March 11th, 2012' ), array( 'v' => 56872 ), ), ), 

This makes the value of f displayed in the tooltip (yay!), But the value of v is still used for axis labels. Hm.

EDIT No. 2

There seems to be some potential in using a DataView to convert the number timestamp to a date, but I haven't figured it out yet.

+8
json javascript google-visualization
source share
2 answers

In the end, I just went over to the JSON array and replaced the timestamps with Date objects. It was easier than I expected:

 for ( var i = 0; i < json.rows.length; i++ ) { json.rows[i].c[0].v = new Date( json.rows[i].c[0].v * 1000 ); } 
+8
source share

I used a string instead of a date type when displaying Date on the x axis. This allowed me to customize the display of DateTime on the server side, formatting it as a string, and also there is no need for tricks, such as creating a date object from some string or numeric values ​​in javascript.

0
source share

All Articles