jdk8带来了新的时间工具类,主要有LocalDateTime(时间+日期) ,LocalDate(日期) 以及LocalTime(时间)。下面来看看常用用法在新的工具类上如何使用。
1. 获取当前的时间
LocalDateTime.now()
LocalDate.now()
LocalTime.now()
获取当前时间很简单,直接调用now方法就可以,上述代码运行结果如下
2019-08-23T16:17:18.439679
2019-08-23
16:17:18.441228
2. 获取其他时区时间
1 获取utc标准时间
LocalDateTime.now(ZoneId.of("UTC"))
LocalDate.now(ZoneId.of("UTC"))
LocalTime.now(ZoneId.of("UTC"))
运行结果如下
2019-08-23T08:20:34.065057
2019-08-23
08:20:34.065973
可以看出比第一次运行的时候少了8个小时,因为北京时间是东8区,所以会比utc标准时间多上8个小时。
2 根据utc为标准获取其他时区时间
LocalDateTime.now(ZoneId.of("+7"))
LocalDate.now(ZoneId.of("+7"))
LocalTime.now(ZoneId.of("+7"))
根据utc标准获取其他时区时间很简单,东区就+,西区就-;
3. 时间格式化和字符串转换时间
1 格式化时间
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now())
DateTimeFormatter.ofPattern("yyyy_MM_dd").format(LocalDate.now())
DateTimeFormatter.ofPattern("HHmmss").format(LocalTime.now())
DateTimeFormatter是定义时间格式的工具类。三个类都可以使用,但是要注意LocalDate不要定义时间格式,LocalTime不要定义日期格式,否则会报错。
2 格式化字符串转时间
LocalDateTime.parse("20190801000000", DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
4.新建需要的时间
LocalDateTime.of(2018, 8, 13, 23, 56, 2)
根据年月日时分秒可以直接新建时间,非常方便。
5.时间和时间戳相互转换
1、时间转时间戳
LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()
2、时间戳转时间
LocalDateTime.ofInstant(Instant.ofEpochMilli(1566550144837L), ZoneId.systemDefault())
6.时间的计算
1、获取一个某个时间的年月日时分秒属性
LocalDateTime now = LocalDateTime.now();
now.getYear();
now.getMonth();
now.getDayOfMonth();
now.getDayOfYear();
now.getDayOfWeek();
now.getHour();
now.getMinute();
now.getSecond();
2、计算某个日期的增减
LocalDateTime now = LocalDateTime.now();
//增加一年
now.plusYears(1);
//减少一年
now.minusYears(1);
//增加一月
now.plusMonths(1);
//减少一月
now.minusMonths(1);
.......
3、计算两个日期之间的差值
LocalDateTime time1 = LocalDateTime.of(2019, 8, 31, 0, 0);
LocalDateTime time2 = LocalDateTime.of(2019, 7, 31, 0, 0);
System.out.println(time1.until(time2,ChronoUnit.DAYS));
result : -31
很方便就可以计算出两个日期之间相差的天数,想要计算其他值也是一样。
4、计算这个地方留个小彩蛋吧
LocalDateTime time2 = LocalDateTime.now().minusDays(1);
LocalDateTime time1 = LocalDateTime.now();
System.out.println(time2.until(time1,ChronoUnit.DAYS));
-----------
LocalDateTime time1 = LocalDateTime.now();
LocalDateTime time2 = LocalDateTime.now().minusDays(1);
System.out.println(time2.until(time1,ChronoUnit.DAYS));
看看两个计算出的结果,和你想的一不一样呢。