简体   繁体   中英

Django DateTimeField display correct timezone (JavaScript)

In a view that displays my calls (Django model) by "start" time, where I use

{{ call.start|date:"H:i:s, m/d/Y" }}

I get the correct timezone, eg 23:36:34, 02/15/2014.

But for the same call, when I am using a Google Chart to graph call start times, the following code puts the aforementioned call in the wrong bin, and the time calculated is 04:36:34.

function drawChart2() {
    var callArray = {{ calls|safe }};
    var calls = [];
    calls[0] = ['Call', 'Time'];
    for (var i = 1; i < callArray.length; i++) {
        call_fields = callArray[i].fields;
        if (call_fields.address != "") {
            call_display = call_fields.address;
        }
        else {
            call_display = call_fields.building;
        }
        if (call_fields.start != "") {
            call_start = call_fields.start;
        }
        hour = parseInt(call_start.slice(11, 13), 10);
        min = parseInt(call_start.slice(14, 16), 10);
        sec = parseInt(call_start.slice(18, 20), 10);
        if (hour == 5 && min == 0)
            continue;
        else
            calls.push([call_display, hour + (1/60) * min + (1/3600) * sec]);
    }

    var time_data = google.visualization.arrayToDataTable(calls)
    var options = {
      title: 'Times of calls by hour',
      legend: { position: 'none' },
    };

    var chart = new google.visualization.Histogram(document.getElementById('hist_div'));
    chart.draw(time_data, options);
  }

Any idea how to get the right timezone? My theory of why I get the wrong timezone is because Django gives the time in terms of the browser's timezone in the template, but when I use it in JavaScript, I'm only pulling the fields straight from how they're stored (UTC) in the JS variable and Django cannot dynamically fix the timezone for display.

There is a much more elegant way to pass the calls list to JavaScript. The following code uses DjangoJSONEncoder which knows how to encode date/time objects correctly:

import json
from django.core.serializers.json import DjangoJSONEncoder

calls = Call.objects.filter(something=something_else) # Assuming this is your calls object

calls_json = json.dumps(list(calls), cls=DjangoJSONEncoder)

In your template, you can use it like:

var callArray = {{ calls_json }};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM