Java 中的日历类方法似乎没有给出正确的结果

问题描述 投票:0回答:1

有人可以解释一下为什么下面这段代码的行为不符合预期吗?

import java.util.Calendar;
import java.util.Date;
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(); 
        String expectedExpiryDate = new SimpleDateFormat("MMMM d, YYYY").format(date); //expected date should be December 28, 2026
        System.out.println(expectedExpiryDate + " expectedExpiryDate");// But we are getting output as December 28, 2027

    }

}

enter image description here

如果我们在今天的日期上添加 1 年,那么我们确实会得到预期的结果,即 2024 年 12 月 28 日。但是,如果我们在今天的日期上添加 2 或 3 年,则分别变为 2026 年 12 月 28 日和 2027 年 12 月 28 日

java date calendar simpledateformat
1个回答
0
投票

停止使用

Calendar
。该类是一个遗留类,很久以前就被 JSR 310 中定义的现代 java.time 类取代。切勿使用
Calendar
SimpleDateFormat
Date
Date
Timestamp

捕获特定时区的当前日期和时间。

ZoneId zoneTokyo = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime nowTokyo = ZonedDateTime.now( zoneTokyo ) ;

增加三年。

ZonedDateTime threeYearsLater = nowTokyo.plusYears( 3 ) ;
© www.soinside.com 2019 - 2024. All rights reserved.