Java8 日期时间API
Contents
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);
解析日期
注意, 这里不同
@Test
public void testParse(){
final String d = "2018-01-01";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("y-M-d");
System.out.println(LocalDate.parse(d, dateTimeFormatter));
}
这个可以同时解析 2018-1-1 或 2018-01-01 这种格式
@Test
public void testParse(){
final String d = "2018-01-01";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(LocalDate.parse(d, dateTimeFormatter));
}
这种则只能解析 2018-01-01 这种格式. 但不能解析 2018-1-1 这种格式
以下是一种错误的示例:
@Test
public void testParse(){
final String d = "2018-1-1";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(LocalDate.parse(d, dateTimeFormatter));
}
它会报:
java.time.format.DateTimeParseException: Text '2018-1-1' could not be parsed at index 5
LocalDateTime 转换为毫秒
LocalDateTime ldt = ....
ZonedDateTime zonedDateTime = ldt.atZone(ZoneId.systemDefault());
long ms = zonedDateTime.toInstant().toEpochMilli();
LocalDate 转换为毫秒
@Test
public void testMs(){
long s = LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(s);
}
毫秒 转换为 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());
dayDiff
@Test
public void daysDiff() {
LocalDate now = LocalDate.now();
LocalDate yes = now.minusDays(1);
System.out.println(ChronoUnit.DAYS.between(now, yes));//-1
System.out.println(ChronoUnit.DAYS.between(yes, now));//1
}