1 LocalDate转换成Date
LocalDate nowLocalDate = LocalDate.now();
Date date = Date.from(nowLocalDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
2 LocalDateTime转换成LocalDate
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = LocalDate.from(localDateTime);
3 比较大小
public static void main(String[] args) {
// 今天
LocalDate today = LocalDate.now();
// 明天
LocalDate tomorrow = today.plusDays(1);
// true-大于;false-不大于
System.out.println(today.isBefore(tomorrow));
// true-小于;false-大于
System.out.println(today.isAfter(tomorrow));
// true-相等;false-不相等
System.out.println(today.equals(LocalDate.now()));
}
true
false
true
4 获取年,月,日,周几
public static void main(String[] args) {
// 获取当前时间
LocalDate localDateTime = LocalDate.now();
System.out.println("当前时间为:" + localDateTime);
// 获取当前月份
System.out.println("当前月份为:" + localDateTime.getMonthValue());
// 获取当前日期
System.out.println("当前日期为:" + localDateTime.getDayOfMonth());
// 今天是周几
System.out.println("今天是周几:" + localDateTime.getDayOfWeek().getValue());
}
当前时间为:2021-04-30
当前月份为:4
当前日期为:30
今天是周几:5
5 获取前一天,后一天
public static void main(String[] args) {
// 今天
LocalDate today = LocalDate.now();
System.out.println(today);
// 昨天
LocalDate yestDay = today.plusDays(-1);
System.out.println(yestDay);
// 明天
LocalDate tomorrow = today.plusDays(1);
System.out.println(tomorrow);
}
2021-04-30
2021-04-29
2021-05-01
6 Long时间转LocalDate
public static LocalDate long2LocalDate(long time) {
ZonedDateTime zonedDateTime = new Date(time).toInstant().atZone(ZoneId.systemDefault());
return zonedDateTime.toLocalDate();
}
7 Long时间转LocalDateTime
public static LocalDateTime long2LocalDateTime(long time) {
ZonedDateTime zonedDateTime = new Date(time).toInstant().atZone(ZoneId.systemDefault());
return zonedDateTime.toLocalDateTime();
}
8 LocalDate转Long
public static long localDate2Long(LocalDate localDate) {
return localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
8 LocalDateTime转Long
public static long localDateTime2Long(LocalDateTime localDateTime) {
return localDateTime.toInstant(ZONE_OFFSET).toEpochMilli();
}