import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CompareDateTime {
public static void main(String[] args) {
// 定义日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 创建两个 LocalDateTime 对象
LocalDateTime dateTime1 = LocalDateTime.parse("2023-10-01 12:30:00", formatter);
LocalDateTime dateTime2 = LocalDateTime.parse("2023-10-02 14:45:00", formatter);
// 比较两个时间
if (dateTime1.isBefore(dateTime2)) {
System.out.println("dateTime1 在 dateTime2 之前");
} else if (dateTime1.isAfter(dateTime2)) {
System.out.println("dateTime1 在 dateTime2 之后");
} else {
System.out.println("dateTime1 和 dateTime2 相等");
}
}
}
java.time.LocalDateTime
和 java.time.format.DateTimeFormatter
来处理和解析日期时间。DateTimeFormatter
来指定日期时间的格式,这里使用的是 yyyy-MM-dd HH:mm:ss
格式。LocalDateTime
对象:通过 LocalDateTime.parse
方法将字符串解析为 LocalDateTime
对象。isBefore
, isAfter
, 和 equals
方法来比较两个 LocalDateTime
对象的时间大小,并输出相应的结果。上一篇:java map 按key排序
下一篇:java mockito
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站