Java中的Calendar类方法似乎没有给出正确的结果[重复]

jm81lzqq  于 5个月前  发布在  Java
关注(0)|答案(2)|浏览(38)

此问题在此处已有答案

Why does sdf.format(date) converts 2018-12-30 to 2019-12-30 in java? [duplicate](3个答案)
5天前关闭。
有人能解释一下为什么下面这段代码的行为不符合预期吗?

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(); 
        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日

6tr1vspr

6tr1vspr1#

tl;dr

LocalDate.now().plusYears( 3 ).toString()

字符串

避免使用旧的日期时间类

停止使用Calendar。该类是一个遗留类,很久以前就被JSR 310中定义的现代 java.time 类所取代。永远不要使用CalendarSimpleDateFormatDateDateTimestamp等。
不要浪费时间去理解这些遗留的日期-时间类。它们有严重的缺陷,有奇怪的功能。它们完全被 java.time 取代,所以继续前进。Sun,Oracle和JCP社区已经。

java.time

仅捕获当前日期,不带时间和时区,使用java.time.LocalDate
确定当前日期需要一个时区。如果省略,则隐式应用JVM的当前默认时区。

ZoneId zoneTokyo = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate todayTokyo = LocalDate.now( zoneTokyo ) ;


加三年。

LocalDate threeYearsLater = todayTokyo.plusYears( 3 ) ;


要生成标准ISO 8601格式的文本,请调用toString。要生成本地化格式的文本,请使用DateTimeFormatter.ofLocalizedDate
一定要指定你想要的/期望的locale。依赖JVM当前的默认语言环境可能是冒险的。隐式地这样做(通过省略任何语言环境的提及)会让用户怀疑你是否知道本地化是如何工作的。

Locale locale = Locale.US;
DateTimeFormatter f = 
        DateTimeFormatter
                .ofLocalizedDate ( FormatStyle.LONG )
                .withLocale ( locale );
String output = threeYearsLater.format ( f );


产量= 2026年12月30日

uurv41yg

uurv41yg2#

我遇到了org.joda.time包,它似乎提供了预期的输出。

import org.joda.time.LocalDateTime;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Test {

public static void main(String[] args) {
    LocalDateTime currentLocalDateTime = LocalDateTime.now();
    LocalDateTime expectedDate = currentLocalDateTime.plus(new Period().withYears(3));
    DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM d, YYYY");
    String dateString = formatter.print(expectedDate);
    System.out.println(dateString);

}

字符串
}

相关问题