Java如何比较两个LocalDate日期大小

IT 文章2年前 (2023)发布 小编
0 0 0

学习比较两个LocalDate实例,以找出与第二个日期相比哪个日期代表较早的日期。LocalDate类是Java 8中添加的java.time包的一部分。

1.isAfter(),isBefore()和isEqual()方法

比较两个LocalDate对象的推荐方法是使用提供的方法之一。这些方法比较两个LocalDate对象并返回一个布尔值-true或false。这些方法只考虑两个日期在本地时间线上的位置,不考虑年代,或日历系统。

  • isAfter(LocalDate other) – 检查给定日期是否在另一个日期之后。
  • isBefore(LocalDate other) – 检查给定日期是否在另一个日期之前。
  • isEqual(LocalDate other) – 检查给定日期是否等于另一个日期。
LocalDate today = LocalDate.now();
LocalDate pastDate = LocalDate.parse("2023-01-04");
boolean isBefore = today.isBefore(pastDate);	//false
boolean isAfter = today.isAfter(pastDate);		//true
boolean isEqual = today.
	isEqual(LocalDate.of(2023, 1, 9));	//false

2.LocalDate compareTo()方法

该compareTo()方法比较两个实例的基于日期的值(天数,月份,年份)并返回基于比较的整数值。

ad

程序员导航

优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站

public int compareTo(ChronoLocalDate otherDate)
  • 0(零):表示两个日期在日历上是相同的日期。
  • 正整数:表示给定日期晚于otherDate。
  • 负整数:表示给定日期早于otherDate。
LocalDate today = LocalDate.now();
LocalDate pastDate = LocalDate.parse("2022-01-04");
int compareValue = today.compareTo(pastDate);
if (compareValue > 0) {
  System.out.println("today is latter than 4th-Jan-2022");
} else if (compareValue < 0) {
  System.out.println("today is earlier than 4th-Jan-2022");
} else {
  System.out.println("both dates are equal");
}

3.LocalDate equals()方法

如果我们只想检查两个日期是否相等(即是否代表相同的日历日),我们可以使用equals()方法。
该boolean equals(LocalDate otherDate)方法返回:

  • true – 给定日期与otherDate相同。
  • false – 给定日期与otherDate不相同。
boolean isEqual = LocalDate.parse("2019-04-09")
      .equals(LocalDate.of(2019, 4, 9));   //true
loolean isEqual = LocalDate.parse("2019-04-09")
      .equals(LocalDate.of(2019, 1, 1));    //false

以上就是Java如何比较两个LocalDate日期大小的实现方法。

© 版权声明

相关文章

暂无评论

暂无评论...