[英]Django DateTimeField display correct timezone (JavaScript)
In a view that displays my calls (Django model) by "start" time, where I use 在通过“开始”时间显示我的调用(Django模型)的视图中
{{ call.start|date:"H:i:s, m/d/Y" }}
I get the correct timezone, eg 23:36:34, 02/15/2014. 我得到了正确的时区,例如2014年2月15日23:36:34。
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. 但是对于同一呼叫,当我使用Google图表绘制呼叫开始时间图表时,以下代码将上述呼叫放入错误的bin中,计算出的时间为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. 我之所以会选择错误的时区,是因为Django在模板中根据浏览器的时区给出了时间,但是当我在JavaScript中使用时,我只是直接从字段的存储方式中提取字段(UTC)在JS变量中,并且Django无法动态修复时区以进行显示。
There is a much more elegant way to pass the calls list to JavaScript. 有一种更加优雅的方法可以将调用列表传递给JavaScript。 The following code uses DjangoJSONEncoder which knows how to encode date/time objects correctly: 以下代码使用DjangoJSONEncoder ,它知道如何正确编码日期/时间对象:
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 }};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.