Search code examples
arraysdatatabledate-formatcalculated-columnsgoogle-datatable

Google datatable - converting "date" string into actual new Date() for entire column (setCell??)


I'm creating a very simple array (I have to list first row as titles?) and parsing it from views.py to template...

def index(request):
    array = [['date','a','b'],["2014,3,3", 10, 8], ["2014,8,3", 6, 4]]
    return render_to_response('template/index.html',  {'array': json.dumps(array)})

In my template I'm doing some JS to create a google chart, which works completely fine.

var djangoData = {{ array|safe }};
      var data = google.visualization.arrayToDataTable(djangoData);

The issue is that on my chart, the dates are just strings, so If I did multiple rows there would be no taking into account of actual date-time.

How do I convert the columns into google new date(yy/mm/dd/hh/mm/ss) etc ?

I've tried loads of things like setCell, setValue but nothing has seemed to work. If a setCell worked I would have tried a method like setColumn too.

my (not working) setCell method code was this:

  data.setCell(1,0,(data.getCell(1,0)));
  data.setCell(2,0,(data.getCell(2,0)));

Trying to change the given date-element in the array of "2014,3,3" into a recognised google table date...

It seems like a really simple problem, but I'm struggling :(

Thanks,

Fred


Solution

  • Important to note that as per the question linked, it is not possible to change a data type of a column. This is why when I tried to convert and replace, it won't work. Link: Google Visualization Changing Column Data Type

    In the google doc's one can see there are no set-type functions, just property/value/label. But unless I just missed it, I didn't see it stated that it wasn't possible to do this with a column.

    In any case, I used the replace column technique he/she demonstrated, making some changes to make it work for a date:

       data.insertColumn(0, 'date', data.getColumnLabel(0));
        // copy values from column 1 (old column 0) to column 0, converted to numbers
        for (var i = 0; i < data.getNumberOfRows(); i++) {
    
            val = data.getValue(i, 1);
            //document.write(new Date(val));
    
            data.setValue(i, 0, new Date(val));
        }
        // remove column 1 (the old column 0)
        data.removeColumn(1);