import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;import java.util.Date; public class TimeCompare { public static void main(String[] args) { // String time1 = "2019-06-26 19:00:00"; // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//有漏洞,建议不要用 // Date date1; // try { // date1 = sdf.parse(time1); // Date date2 = new Date(); // System.out.println(date1.before(date2)); // System.out.println(date1.after(date2)); // } catch (ParseException e) { // e.printStackTrace(); // } //第一种 String time1 = "2019-06-26 19:00:00"; DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime = LocalDateTime.parse(time1, dtf2); System.out.println(localDateTime.isBefore(LocalDateTime.now()));//你的时间在当前时间之前是true System.out.println(localDateTime.isAfter(LocalDateTime.now()));//在当前时间之后是false
//第二种
LocalDateTime now = LocalDateTime.now();
Duration duration = Duration.between(now,now);
System.out.println(duration);
long days = duration.toDays(); //相差的天数
long hours = duration.toHours();//相差的小时数
long minutes = duration.toMinutes();//相差的分钟数
long millis = duration.toMillis();//相差毫秒数
long nanos = duration.toNanos();//相差的纳秒数
System.out.println(millis);
//第三种
long mills = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(mills >= System.currentTimeMillis());
} }