You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Thymeleaf:如何根据月份数字显示月份名称

在Thymeleaf中将Integer类型的月份数字转为月份名称

方法一:使用Thymeleaf内置的#calendars工具类

#dates工具类主要处理Date对象,而#calendars可直接基于月份数字生成对应名称。你的月份数字0对应January,刚好匹配Java Calendar类的月份索引规则(0=1月,11=12月),写法如下:

<span th:text="${#calendars.monthName(#calendars.create(2000, monthNum, 1), 'ENGLISH')}"></span>
  • #calendars.create(2000, monthNum, 1):创建指定月份的Calendar实例,年份和日期填合法值即可,不影响月份名称获取
  • 'ENGLISH'指定语言,确保返回英文月份名称,也可按需替换为其他语言代码

方法二:后端自定义映射(推荐)

在DTO类中添加获取月份名称的方法,后端完成转换后前端直接取值:

public class YourDto {
    private Integer monthNum;

    // getter、setter省略

    public String getMonthName() {
        String[] months = {"January", "February", "March", "April", "May", "June", 
                          "July", "August", "September", "October", "November", "December"};
        if (monthNum != null && monthNum >= 0 && monthNum <= 11) {
            return months[monthNum];
        }
        return "Unknown";
    }
}

前端调用:

<span th:text="${yourDto.monthName}"></span>

方法三:Thymeleaf switch语句手动映射

如果场景简单,可直接在模板中硬映射:

<th:block th:switch="${monthNum}">
    <span th:case="0">January</span>
    <span th:case="1">February</span>
    <span th:case="2">March</span>
    <span th:case="3">April</span>
    <span th:case="4">May</span>
    <span th:case="5">June</span>
    <span th:case="6">July</span>
    <span th:case="7">August</span>
    <span th:case="8">September</span>
    <span th:case="9">October</span>
    <span th:case="10">November</span>
    <span th:case="11">December</span>
    <span th:case="*">Unknown</span>
</th:block>

内容的提问来源于stack exchange,提问作者itsraja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 00:18:12