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

Java Calendar类日期计算结果不符预期,求原因解析

问题原因分析

你的代码输出不符合预期的核心问题是误用了日期格式化的年份模式:

  • 你使用的大写YYYY代表周年(Week Year),它是基于周的年份计算规则,而非日常使用的公历年。
  • 正确表示公历年的格式应该是小写的yyyy。

为什么会出现2027的结果?

当日期为2026年12月28日时,按照SimpleDateFormat采用的美国周历规则(周日为一周起始),这一天所在的周包含2027年1月1日,因此该周被归为2027年的第一周,YYYY便会返回2027,而非实际的公历年2026。

同理,添加2年得到的2025年12月28日,若所在周包含2026年1月1日,也会被YYYY格式化为2026年。

修复后的代码

只需将YYYY替换为yyyy即可得到正确结果:

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat; 
public class Test {

    public static void main(String[] args) {
        int numberOfYears = 3;
        Calendar now = Calendar.getInstance();//Today's date is December 28, 2023
        now.add(Calendar.YEAR, numberOfYears);// Adding 3 years to it
        Date date = now.getTime(); 
        // 替换YYYY为yyyy
        String expectedExpiryDate = new SimpleDateFormat("MMMM d, yyyy").format(date); 
        System.out.println(expectedExpiryDate + " expectedExpiryDate");// 输出December 28, 2026
    }

}

额外建议

Calendar和SimpleDateFormat是Java旧版日期API,存在线程不安全、设计不直观等问题。推荐使用Java 8及以上版本的java.time新日期API,示例如下:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Test {
    public static void main(String[] args) {
        int numberOfYears = 3;
        LocalDate now = LocalDate.of(2023, 12, 28);
        LocalDate expiryDate = now.plusYears(numberOfYears);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy");
        String expectedExpiryDate = expiryDate.format(formatter);
        System.out.println(expectedExpiryDate + " expectedExpiryDate");
    }
}

新API线程安全,逻辑更清晰,能避免旧API的诸多陷阱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:26:05