如何在Java中比较两个日期和时间?
该java.time.LocalDateTime 类表示本地日期和时间,即无时区的日期,你可以使用这个对象,而不是日期。这个类提供了各种方法,例如isBefore(),isAfter()和,isEqual()来比较两个日期-
示例
import java.time.LocalDateTime; public class Test { public static void main(String args[]) { LocalDateTime dateTime1 = LocalDateTime.of(2007, 11, 25, 10, 15, 45); LocalDateTime dateTime2 = LocalDateTime.of(1999, 9, 12, 07, 25, 55); Boolean bool1 = dateTime1.isAfter(dateTime2); Boolean bool2 = dateTime1.isBefore(dateTime2); Boolean bool3 = dateTime1.isEqual(dateTime2); if(bool1){ System.out.println(dateTime1+" 是在之后 "+dateTime2); }else if(bool2){ System.out.println(dateTime1+" 是之前 "+dateTime2); }else if(bool3){ System.out.println(dateTime1+" 等于 "+dateTime2); } } }输出结果
2007-11-25T10:15:45 是在之后 1999-09-12T07:25:55
示例
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class CreateDateTime { public static void main(String args[]) throws ParseException { String dateTimeStr1 = "26-09-1989 8:27:45"; String dateTimeStr2 = "12-11-2010 2:30:12"; //实例化SimpleDateFormat类 SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:SS"); Date dateTime1 = formatter.parse(dateTimeStr1); Date dateTime2 = formatter.parse(dateTimeStr2); Boolean bool1 = dateTime1.after(dateTime2); Boolean bool2 = dateTime1.before(dateTime2); Boolean bool3 = dateTime1.equals(dateTime2); if(bool1){ System.out.println(dateTimeStr1+" 是在之后 "+dateTimeStr2); }else if(bool2){ System.out.println(dateTimeStr1+" 是之前 "+dateTimeStr2); }else if(bool3){ System.out.println(dateTimeStr1+" 等于 "+dateTimeStr2); } } }输出结果
26-09-1989 8:27:45 是之前 12-11-2010 2:30:12