Search code examples
javascriptchart.jsluxon

How do I incorporate Luxon timezone options with chart.js?


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/luxon@1.15.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@0.2.0"></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.


Solution

  • 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/