Java 8中表示日期和时间的类有多个,主要的有:
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String localTime = df.format(time);
LocalDateTime ldt = LocalDateTime.parse("2018-06-01 10:12:05",df);
System.out.println("LocalDateTime转成String类型的时间:"+localTime);
System.out.println("String类型的时间转成LocalDateTime:"+ldt);
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
LocalDateTime now = LocalDateTime.now();
LocalDate localDate = now.toLocalDate();
LocalDate localDate = LocalDate.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
LocalDateTime now = LocalDateTime.now();
//明天
LocalDateTime plusDays = now.plusDays(1);
//昨天
LocalDateTime plusDays2 = now.plusDays(-1);
//还有时分等同理
LocalDateTime now = LocalDateTime.now();
Long epochMilli = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
然后比较long就可以了
默认时区是ZoneId.systemDefault()
使用Duration进行 day,hour,minute,second等的计算
使用Period进行Year,Month的计算
Duration duration = Duration.between(localDateTime,localDateTime4);
duration.toDays();
duration.toHours();
duration.toMinutes();
Period period2 = Period.between(localDateTime.toLocalDate(),localDateTime4.toLocalDate());
period2.getYears();
period2.getMonths();
period2.toTotalMonths();
String time = "2018-08-09 11:20:45";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
LocalDateTime localTime = LocalDateTime.parse(time, dtf);
LocalDateTime startTime = LocalDate.now().atTime(0, 0, 0);
LocalDateTime endTime = LocalDate.now().atTime(23, 59, 59);
LocalDateTime startYesterday = LocalDate.now().plusDays(-1).atTime(0, 0, 0);
LocalDateTime endYesterday = LocalDate.now().plusDays(-1).atTime(23, 59, 59);
//如果小于昨天的开始日期
if (localTime.isBefore(startYesterday)) {
System.out.println("时间是过去");
}
//时间是昨天
if (localTime.isAfter(startYesterday) && localTime.isBefore(endYesterday)) {
System.out.println("时间是昨天");
}
//如果大于今天的开始日期,小于今天的结束日期
if (localTime.isAfter(startTime) && localTime.isBefore(endTime)) {
System.out.println("时间是今天");
}
//如果大于今天的结束日期
if (localTime.isAfter(endTime)) {
System.out.println("时间是未来");
}