Java 8 中, 将日期和时间, 以及日期时间可以分别处理的

获取当前日期

LocalDate.now(); //2018-05-18

获取当前时间

LocalTime.now(); //13:48:37.127

去掉纳秒:
LocalTime.now().withNano(0); //13:49:03

格式化日期

DateTimeFormatter 对象是不可变的, 也就是线程安全的~

private static final DateTimeFormatter NGINX_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z");

String dateStr = "18/May/2018:11:01:03 +0800";
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, NGINX_TIME_FORMATTER);

LocalDateTime 转换为毫秒

LocalDateTime ldt = ....

ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
long ms = zonedDateTime.toInstant().toEpochMilli();

毫秒 转换为 LocalDateTime 或 LocalDate 或 LocalTime

long ms = ...
LocalDate date = Instant.ofEpochMilli(ms).atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate date = Instant.ofEpochMilli(1526615212000L).atZone(ZoneId.systemDefault()).toLocalTime();
LocalDate date = Instant.ofEpochMilli(1526615212000L).atZone(ZoneId.systemDefault()).toLocalDateTime();

时间戳

Instant instant = Instant.now();//2018-05-18T05:57:12.586Z

日期时间的加减

绝大部分的日期时间对象, 它会提供 plus , minus 方法来进行加减的.

LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTimePlus1 = localDateTime.plusDays(1);
System.out.println(localDateTime);
System.out.println(localDateTimePlus1);

输出结果

2018-05-18T14:01:22.687
2018-05-19T14:01:22.687

其他的类似

Date 转换为 LocalDateTime

Date date = new Date();
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());