工作时用到的记录一下,方便再次使用时查找(跟着工作持续更新)
1.获取一个日期到此次日期的月底距离多少天
// 获取当前时间--也可以自定义时间然后转为LocalDateTime即可
LocalDateTime localDate = LocalDateTime.now();
// 获取此次日期的月底时间
LocalDateTime lastDayMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
// 获取距离月底差多少天
System.out.println(lastDayMonth.getDayOfMonth() - localDate.getDayOfMonth());
2.Date转LocalDate || LocalDateTime
// Date转LocalDate
new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// Date转LocalDateTime
new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
3.localDateTime转Date(LocalDate也一样这里就不写了)
Date nowDate = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant())
4.格式化日期<->字符串转日期
// 日期转字符串
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("LocalDateTime转字符串:" + dateTimeFormatter.format(localDateTime));
// 字符串转日期
String dateStr = "2019-06-13 16:26:56";
LocalDateTime stringToLocalDateTime = LocalDateTime.parse(dateStr,dateTimeFormatter);
System.out.println("字符串转日期:" + stringToLocalDateTime);
// 输出结果
// LocalDateTime转字符串:2019-06-13 16:31:14
// 字符串转日期:2019-06-13T16:26:56
5.计算当前日期至某个日期距离的天数
// 当前时间
LocalDateTime localDateTime = LocalDateTime.now();
// 获取下个月1号时间
LocalDateTime nextLocalDateTime = localDateTime.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
// 比对时间
Duration duration = Duration.between(localDateTime,nextLocalDateTime);
// 相差小时
System.out.println(duration.toHours());
// 相差天数
System.out.println(duration.toDays());
// 或者 不用Duration.between 直接使用until 其实这个方法里面也是调用的between
System.out.println(localDateTime.until(nextLocalDateTime, ChronoUnit.HOURS));