Search code examples
javajfreechart

JFreeChart - TimeSeries with respect to TimeZone


Good day, dear colleagues.

I have data with UTC datetime. While creating the chart, I'd like to convert time to Local time with respecting the timezone set on host machine. Is there a way to do this for TimeSeries?

private XYDataset createDataset(Set<Parameters> parameters) {
        var s1 = new TimeSeries("Series1 title");
        for (Parameters p : parameters) {
            s1.addOrUpdate(new Second(p.getDatetime()), p.getTVol()); // <-- p.getDateTime() returns java.util.Date in UTC
        }
        var dataset = new TimeSeriesCollection();
        dataset.addSeries(s1);
        return dataset;
    }

Solution

  • As you've observed, your chosen Second constructor accepts a java.util.Date that reflects an instant in coordinated universal time (UTC). An alternative to this approach is to defer the conversion from UTC to local time until the value is displayed in the view. As your time series chart likely uses a DateAxis for the domain, you will find that local times are displayed by default; use setDateFormatOverride() to change the default display. In this example, the axis is conditioned to display UTC:

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ssX");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    axis.setDateFormatOverride(df);
    

    For comparison, hover over a data point to see the tooltip, which displays the corresponding time in the host platform's local time. Additional examples may be found here.