JFreeChart - 关于 TimeZone 的 TimeSeries

JFreeChart - TimeSeries with respect to TimeZone

美好的一天,亲爱的同事们。

我有 UTC 日期时间的数据。 在创建图表时,我想根据主机上设置的时区将时间转换为本地时间。有没有办法为 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;
    }

好吧,我通过以下技巧关闭了问题:

private Date convertUtcToLocalDateTime(Date date) {
        var dtfUtc = new SimpleDateFormat(dateTimeFormat);
        dtfUtc.setTimeZone(TimeZone.getTimeZone("0"));
        var dtfLocal = new SimpleDateFormat(dateTimeFormat);
        try {
            return dtfUtc.parse(dtfLocal.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }

如果有人能提出更好的解决方案 - 我将不胜感激

如您所见,您选择的 Second constructor accepts a java.util.Date that reflects an instant in coordinated universal time (UTC). An alternative to this 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 坐标轴已调整为显示 UTC:

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

为了进行比较,将鼠标悬停在数据点上以查看工具提示,其中显示主机平台本地时间的相应时间。可以在 here.

中找到其他示例