示例示例Java中比较两个时间的常用方法有两种:使用java.util.Date类的()方法:
Java中比较两个时间的常用方法有两种:
1. 使用java.util.Date类的compareTo()方法:
该方法比较两个日期对象,如果日期对象date1小于date2,则返回-1;如果date1等于date2,则返回0;如果date1大于date2,则返回1。
代码示例:
import java.util.Date;
public class DateCompare {
public static void main(String[] args) {
Date date1 = new Date(2020, 3, 1);
Date date2 = new Date(2020, 4, 1);
int result = date1.compareTo(date2);
System.out.println("result:" + result);
}
}
2. 使用java.time.LocalDateTime类的isBefore()和isAfter()方法:
该方法比较两个LocalDateTime对象,如果LocalDateTime对象dateTime1在dateTime2之前,则返回true;如果dateTime1在dateTime2之后,则返回false。
代码示例:
import java.time.LocalDateTime;
public class DateTimeCompare {
public static void main(String[] args) {
LocalDateTime dateTime1 = LocalDateTime.of(2020, 3, 1, 0, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.of(2020, 4, 1, 0, 0, 0);
boolean result = dateTime1.isBefore(dateTime2);
System.out.println("result:" + result);
}
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(58条)