Search code examples
javascriptjquerydygraphs

How to format date and time in Dygraphs legend according to user locale


I have a graph that displays a device's power output over time and I'd like to format the legend so that it displays the timestamps in the style of where the current user is (for example, in the US it would show MM/DD/YY h:m:s am/pm, and in EU would show DD/MM/YYYY HH:MM:SS, etc.).

Currently, it's set at default, as follows:

enter image description here

I pass in a JS Date() object for the x-axis and I've found that you can modify the x-axis labels, but I can't find any info on changing the format of the legend when hovering over the graph.


Solution

  • You've discovered the axisLabelFormatter option, which lets you control formatting of labels on the x-axis.

    To control formatting of labels in the legend, you need to use valueFormatter

    g = new Dygraph(div, data,
        axes: {
            x: {
                axisLabelFormatter: function (d, gran) {
                    return d.toLocaleDateString();
                },
                valueFormatter: function (ms) {
                    return new Date(ms).toLocaleDateString();
                }
            }
        }
    });
    

    See this fiddle for a fully-worked example. Is it odd that one formatter function takes a Date whereas the other takes millis since epoch? Yes. Unfortunately, it's an inconsistency we're stuck with.