文
章
目
录
章
目
录
要学习比较两个LocalDateTime实例,找出哪个日期代表的时间戳比另一个更早。LocalDateTime类是Java 8中添加的java.time包的一部分。
1.isAfter(),isBefore()和isEqual()
比较两个LocalDateTime对象的推荐方法是使用提供的方法,这些方法比较日期时间部分并返回一个布尔值-true或false。这些方法只考虑两个日期在本地时间线上的位置,不考虑年代或日历系统。
- isAfter(otherDateTime) – 检查给定的日期时间是否在另一个日期时间之后。
- isBefore(otherDateTime) – 检查给定的日期时间是否在另一个日期时间之前。
- isEqual(otherDateTime) – 检查给定的日期时间是否等于另一个日期时间。
LocalDateTime now = LocalDateTime.now();
LocalDateTime pastDate = LocalDateTime.parse("2023-01-14T15:32:56.000");
boolean isBefore = now.isBefore(pastDate); //false
boolean isAfter = now.isAfter(pastDate); //true
boolean isEqual = now.isEqual(pastDate); //false
2.LocalDateTime compareTo()方法
该compareTo()方法比较两个本地日期时间对象并返回一个整数值,该值基于比较结果。这些方法不考虑时区或日历信息进行比较。
该int compareTo(otherDateTime)方法返回:
- 0(零)- 如果两个日期时间表示同一天的相同时间点。
- 正整数- 如果给定的日期时间比otherDate晚。
- 负整数- 如果给定的日期时间比otherDate早。
LocalDateTime ldt1 = LocalDateTime.parse("2019-04-28T22:32:38.536");
LocalDateTime ldt2 = LocalDateTime.parse("2017-01-14T15:32:56.000");
int diff = ldt1.compareTo(ldt2);
System.out.println("Compare value = " + diff); //2
if (diff > 0) {
System.out.println("ldt1 is later than ldt2"); //Prints it
} else if (diff < 0) {
System.out.println("ldt1 is earlier than ldt2");
} else {
System.out.println("both dates are equal");
}
3.LocalDateTime equals()方法
如果我们只想检查日期和时间值是否相等(即在本地时间线上表示相同的一天中的同一时间),我们可以使用equals()方法。该方法返回:
- true – 给定的日期与otherDate相同。
- false – 给定的日期与otherDate不相同。
LocalDateTime ldt1 = LocalDateTime.of(2019, 4, 9, 10, 10, 50);
LocalDateTime ldt2 = LocalDateTime.of(2019, 4, 9, 10, 10, 50);
LocalDateTime ldt3 = LocalDateTime.of(2019, 4, 9, 11, 12, 50);
System.out.println(ldt1.equals(ldt2)); //true
System.out.println(ldt1.equals(ldt3)); //false
以上就是Java如何比较两个LocalDateTime日期时间大小的方法。