Reputation: 43
I have a line chart displayed on a webpage with chart.js but my time data is in UTC. I would like to convert it to the Denver timezone for display on the graph. Chart.js has a luxon adapter but I have no idea how to use it.
I have included the following scripts:
<script src="./chart.js/dist/Chart.bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
My time data formatted as a json string:
var data = [{"x":"2019-07-23 01:16:11","y":83.97},{"x":"2019-07-23 01:07:13","y":82.74},{"x":"2019-07-23 00:58:21","y":83.86}, ...
And here are my chart "Options":
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'series',
}]
}
}
So where and how do I implement a timezone definition? I have also looked through the Luxon timezone documentation.
Upvotes: 4
Views: 4520
Reputation: 81
I spent a while trying to get this to work with more recent versions of Chart.js, and the solution turned out to be pretty simple – the zone
option now needs to be specified under options.scales[scaleId].adapters.date
, like so:
options: {
scales: {
xAxes: [{
adapters: {
date: {
zone: 'America/Denver',
},
},
type: 'time',
distribution: 'series',
}],
},
}
Upvotes: 2
Reputation: 2413
The way that adapter seems to work is that it just passes the chart.js options object to the Luxon methods. So you'd want something like:
options: {
// other chart.js options here, and then...
zone: "America/Denver"
}
But that won't fix it on its own. The problem is that you haven't told Luxon that your times are expressed in UTC, and the adapter doesn't give you a way to separately specify the zone you want to parse in vs format in. The easy fix to that is to change your strings to ISO 8601 strings with "Z" on the end to tell anything parsing it that the strings are meant to be interpreted as UTC strings. Then Luxon will parse them in UTC and use the zone option to format them for Denver.
So, 2019-07-23 01:07:13
--> 2019-07-23T01:07:13Z
Here's a fiddle: https://jsfiddle.net/9f0pu7ac/1/
Upvotes: 1