如何使用 LinkedHashMap 中的日期作为 Highcharts 折线图上的 x 轴(使用 Thymeleaf)?

How do I use dates from a LinkedHashMap for the x-axis on a Highcharts line graph (using Thymeleaf)?

我刚开始使用 Highcharts,所以这可能是一个小问题。但是,通过我自己的谷歌搜索,我并没有取得太大的成功。

我试图获得一个折线图来显示强度随时间的变化,但每次我插入 keySet()(java.util.Date 类型)作为 X 轴上的内容时,图从网页上消失。

我希望记录完成的事件及其完成日期是图表上的一个点(即 (x,y) 将是 (action, date))。

Java 东西:

List<StrengthProgressPoint> records = getAllStrengthLogsForExercise(session, exerciseName);
Map<Date, Double> strengthGraph = new LinkedHashMap<>();
for(StrengthProgressPoint p : records) { 
    strengthGraph.put(p.getDate(), p.getWeight()); 
}

Highcharts 资料:

<script>
$(function () {
$('#progressGraphContainer').highcharts({
        title: {
            text: ''
        },

        subtitle: {
            text: ''
        },

        yAxis: {
            min: 0,
            title: {
                text: 'Weight Lifted'
            }
        },

        xAxis: {
            categories: [[${strengthGraph.keySet()}]],
        },

        legend: {
            enabled: false
        },

        plotOptions: {
            series: {
                label: {
                    connectorAllowed: false,
                    connectNulls: true
                },
            }
        },

        series: [{
            name: 'Weight',
            data: [[${strengthGraph.values()}]]
        }],

        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        enabled: false
                    }
                }
            }]
        }
});
});
</script>

我确实在我的网页上显示了几次图表,但从来不是我想要的。我似乎已经将其缩小到 'categories: [[${strengthGraph.keySet()}]]' 是导致图表不显示在网页上的罪魁祸首。我只希望 HashMap 中的日期显示在 x 轴上(当然对应于适当的值)。

因为您将 Thymeleaf 与 JavaScript 一起使用,所以您需要在 <script> 标签中注明:

<script th:inline="javascript">

没有这个,从您的 Java 对象到等效的 JavaScript 对象的渲染将不会发生。

我假设您已经在页面的 <html> 标签中包含了 Thymeleaf 命名空间:

<html xmlns:th="http://www.thymeleaf.org">

日期将显示在 x 轴上 - 但格式可能有点麻烦 - 例如:

2021-03-15T00:00:00.000-04:00

因此,您可以添加标签格式化程序。有很多方法可以格式化日期,我希望 HighCharts 有内置的方法来做到这一点,但我不熟悉它们 - 所以这里是一个简单的 Java脚本方式:

xAxis: {
    categories: [[${strengthGraph.keySet()}]],
    labels: {
        formatter: function () {
            var d = Date.parse(this.value);
            const ye = new Intl.DateTimeFormat('en', {year: 'numeric'}).format(d);
            const mo = new Intl.DateTimeFormat('en', {month: 'short'}).format(d);
            const da = new Intl.DateTimeFormat('en', {day: '2-digit'}).format(d);
            return `${da}-${mo}-${ye}`;
        }
    }

},
...

现在轴将使用这样的标签:

15-Mar-2021

我从 this question 那里获取了这个格式化程序代码,那里还有其他方法。


值得一提:当您将 Thymeleaf 表达式放在 JavaScript 中时,您可以通过将 Thymeleaf 表达式放在注释中并在其位置提供默认值来抑制 JavaScript 语法错误:

categories: /*[[${strengthGraph.keySet()}]]*/ []

在这种情况下,[] 是默认值。当 Thymeleaf 渲染表达式时,它会移除 /**/ 注释分隔符,同时也会移除默认表达式。