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

Java中使用Calendar类无法获取正确当前月份,求解决方法

正确获取当前月份的Java解决方案

问题原因

Calendar.MONTH的取值是从0开始的:0对应1月,1对应2月……11对应12月,所以直接调用calendar.get(Calendar.MONTH)得到的数值会比实际月份小1,这就是你得到错误结果的原因。

解决方案1:修正现有Calendar代码

在获取到的月份值基础上加1,即可得到日常使用的1-12的月份数字:

Calendar calendar = Calendar.getInstance();
// 获取修正后的月份(1-12)
int correctMonth = calendar.get(Calendar.MONTH) + 1;
System.out.println("当前月份:" + correctMonth);

解决方案2:使用Java 8+推荐的java.time API

Calendar是Java遗留的日期类,设计存在诸多缺陷,官方推荐从Java 8开始使用java.time包下的新日期API,更直观且不易出错:

获取数字形式的月份(1-12)

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // 获取当前日期
        LocalDate now = LocalDate.now();
        // 获取1-12的月份数字
        int month = now.getMonthValue();
        System.out.println("当前月份:" + month);
    }
}

获取月份的本地化名称

import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        // 获取中文全称月份(如十月)
        String chineseMonthName = now.getMonth().getDisplayName(TextStyle.FULL, Locale.CHINESE);
        // 获取英文全称月份(如October)
        String englishMonthName = now.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
        System.out.println("中文月份:" + chineseMonthName);
        System.out.println("英文月份:" + englishMonthName);
    }
}

内容的提问来源于stack exchange,提问作者Nguyễn Anh Việt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:30:49