基础用法
LocalDateTime now = LocalDateTime.now()
LocalDateTime转Date
LocalDateTime now = LocalDateTime.now();
ZonedDateTime zonedDateTime1 = now.atZone(ZoneId.systemDefault());
//或者 ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("+8"));
//注意:Instant是桥梁
Date date = Date.from(zonedDateTime.toInstant());
Date转LocalDateTime
Date date = new Date();
Instant instant = date.toInstant();
LocalDateTime now = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
时区
时区用Zone表示,UTC是协调世界时间,中国的时区是正八区(即UTC+8)
所以可以使用ZoneId.of(“+8”)表示中国,或者使用ZoneId.of(“Asia/Shanghai”)
格式化
//格式化当前日期
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String now_date = LocalDateTime.now().format(formatter);
System.out.println(now_date);//20200316
时间间隔
LocalDateTime now = LocalDateTime.now();
LocalDateTime updateTime = node.getUpdateTime();
long duration = Duration.between(now, updateTime).toMillis();
年月日间隔
LocalDate today = LocalDate.now();
for (String uploadKey : uploadKeys) {
//181 21 12 13 0001
//格式说明:
//1-3: 机位
//4-9: 年月日
//10以后: 自增id
String taskKey = uploadKey.replace(RedisUtil.SRS_UPLOAD_SLICE_PREFIX, "");
LocalDate date = LocalDate.parse(taskKey.substring(3, 9), formatter);
long duration = ChronoUnit.DAYS.between(date, today);
if (duration > 2) {
deleteKeys.add(uploadKey);
}
}
比较大小
@Test
public void localDateTimeCompare() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime future = now.plusSeconds(20);
int i = now.compareTo(future);
System.out.println(i);
}