Java8新的时间处理包

   在jdk8中新出了一个时间处理包,试用了一下,日期的加减很方便,以前要用什么joda(我没用过,只听过),好了,废话不多说,看个简单的例子。

LocalDate curDate = LocalDate.now();
LocalDate preDate = curDate.plus(-1, ChronoUnit.DAYS);
LocalDate nextDate = curDate.plus(1, ChronoUnit.DAYS);
System.out.println(preDate);// 2017-06-16
System.out.println(curDate);// 2017-06-17
System.out.println(nextDate);// 2017-06-18


LocalDateTime curDateTime = LocalDateTime.now();
LocalDateTime preDateTime = curDateTime.plus(-1, ChronoUnit.DAYS);
LocalDateTime nextDateTime = curDateTime.plus(1, ChronoUnit.DAYS);

System.out.println(preDateTime);// 2017-06-16T10:21:39.041
System.out.println(curDateTime);// 2017-06-17T10:21:39.041
System.out.println(nextDateTime);// 2017-06-18T10:21:39.041

    用起来,真的很方便,加一天减一天,加一小时,减一小时都是很容易就写出来。

    很多系统还是用的java.util.Date类,既想使用java8中的,又想兼容之前的数据类型,那么就需要他们之间能互相转换就行了。

// date 转 localdate
Date inputDate = new Date();
Instant inputDateInstant = inputDate.toInstant();
ZonedDateTime zdt = inputDateInstant.atZone(ZoneId.systemDefault());
LocalDate outputLocalDate = zdt.toLocalDate();
System.out.println(outputLocalDate);// 2017-08-02

// localdate 转 date
LocalDate inputLocalDate = LocalDate.now();
ZoneId zone = ZoneId.systemDefault();
Instant inputLocalDateInstant = inputLocalDate.atStartOfDay().atZone(zone).toInstant();
java.util.Date outputDate = Date.from(inputLocalDateInstant);
System.out.println(outputDate);// Wed Aug 02 00:00:00 CST 2017

猜你喜欢

转载自kibear.iteye.com/blog/2379909