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

jm81lzqq  于 2024-01-05  发布在  Java
关注(0)|答案(2)|浏览(156)

此问题在此处已有答案

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

  1. import java.util.Calendar;
  2. import java.util.Date;
  3. import java.text.SimpleDateFormat;
  4. public class Test {
  5. public static void main(String[] args) {
  6. int numberOfYears = 3;
  7. Calendar now = Calendar.getInstance();//Today's date is December 28, 2023
  8. now.add(Calendar.YEAR, numberOfYears);// Adding 3 years to it
  9. Date date = now.getTime();
  10. String expectedExpiryDate = new SimpleDateFormat("MMMM d, YYYY").format(date); //expected date should be December 28, 2026
  11. System.out.println(expectedExpiryDate + " expectedExpiryDate");// But we are getting output as December 28, 2027
  12. }
  13. }

字符串
enter image description here
如果我们在今天的日期上加上1年,那么我们确实会得到预期的结果,即2024年12月28日。但是,如果我们在今天的日期上加上2年或3年,那么它分别成为2026年12月28日和2027年12月28日

6tr1vspr

6tr1vspr1#

tl;dr

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

字符串

避免使用旧的日期时间类

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

java.time

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

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


加三年。

  1. LocalDate threeYearsLater = todayTokyo.plusYears( 3 ) ;


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

  1. Locale locale = Locale.US;
  2. DateTimeFormatter f =
  3. DateTimeFormatter
  4. .ofLocalizedDate ( FormatStyle.LONG )
  5. .withLocale ( locale );
  6. String output = threeYearsLater.format ( f );


产量= 2026年12月30日

展开查看全部
uurv41yg

uurv41yg2#

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

  1. import org.joda.time.LocalDateTime;
  2. import org.joda.time.Period;
  3. import org.joda.time.format.DateTimeFormat;
  4. import org.joda.time.format.DateTimeFormatter;
  5. public class Test {
  6. public static void main(String[] args) {
  7. LocalDateTime currentLocalDateTime = LocalDateTime.now();
  8. LocalDateTime expectedDate = currentLocalDateTime.plus(new Period().withYears(3));
  9. DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM d, YYYY");
  10. String dateString = formatter.print(expectedDate);
  11. System.out.println(dateString);
  12. }

字符串
}

展开查看全部

相关问题