今天看企业规范性有写到实体类不能使用date属性,尽量使用localDateTime,很好奇就去学习了下,总结:
1.首先如果使用date类型的话,控制打印的可读性很差
只能通过 SimpleDateFormat 对他进行格式化日期
SimpleDateFormat sdf = new SimpleDateFormat(“yyyyMMdd”);
String format = sdf.format(new Date());
2.SimpleDateFormat 是线程不安全的。当多个线程同时使用相同的SimpleDateFormat对象【如用static修饰的SimpleDateFormat】调用format方法时,多个线程会同时调用calendar.setTime方法,可能一个线程刚设置好time值另外的一个线程马上把设置的time值给修改了导致返回的格式化时间可能是错误的。
3.Date对时间的管理获取比较麻烦,需要调用它的方法getYear、getMonth但是都被弃用了
java8全新的日期和时间API
LocalDateTime
获取年月日时分秒,等于LocalDate+LocalTime
创建LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56);
LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
LocalDateTime localDateTime3 = localDate.atTime(localTime);
LocalDateTime localDateTime4 = localTime.atDate(localDate);
DateTimeFormatter默认提供了多种格式化方式,如果默认提供的不能满足要求,可以通过DateTimeFormatter的ofPattern方法创建自定义格式化方式