Java8之前,时间都是使用Date类,但Date类缺点太多,使用起来很麻烦,Java8的LocalDateTime很好的解决了这个问题
一、LocalDateTime
- 获取当前时刻非常直观
public class Test {
public static void main(String[] args) {
final LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("当前时间:" + localDateTime);
System.out.println("年:" + localDateTime.getYear());
System.out.println("月:" + localDateTime.getMonthValue());
System.out.println("日:" + localDateTime.getDayOfMonth());
System.out.println("时:" + localDateTime.getHour());
System.out.println("分:" + localDateTime.getMinute());
System.out.println("秒:" + localDateTime.getSecond());
}
}
- 构造一个指定的日期非常方便
@org.junit.Test
public void test1() {
final LocalDateTime localDateTime = LocalDateTime.of(2021, Month.MAY, 9, 8, 12, 12);
System.out.println(localDateTime);
}
- 日期修改
public void test2() {
final LocalDateTime localDateTime = LocalDateTime.of(2021, Month.MAY, 9, 15, 34, 12);
System.out.println("减去一天:" + localDateTime.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
System.out.println("修改年份:" + localDateTime.withYear(2022));
System.out.println("减去一年:" + localDateTime.minusYears(1));
}
- 格式化日期
public void test3() {
final LocalDateTime localDateTime = LocalDateTime.now();
final String format1 = localDateTime.format(DateTimeFormatter.ISO_DATE);
final String format2 = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
final String format3 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
System.out.println(format1); // 2021-05-09
System.out.println(format2); // 2021-05-09T16:15:35.236
System.out.println(format3); // 2021-05-09 04:15:35
}
Date和LocalDateTime的转换
/**
* java.util.Date --> java.time.LocalDateTime
*
* @param date Date
* @return LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* java.time.LocalDateTime --> java.util.Date
*
* @param localDateTime LocalDateTime
* @return Date
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
- 转换示例
public LocalDateTime convertDateToLDT(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
@org.junit.Test
public void test4() {
// 日期格式
final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
// 当前日期 Date 类型
final LocalDateTime dateTime = convertDateToLDT(new Date());
// LocalDataeTime 类型 格式化输出
System.out.println(dateTime.format(dateTimeFormatter)); // 2021-05-09 05:15:43
}