java8的时间和Date
的对比
1. LocalDate
,LocalTime
,LocalDateTime
LocalDate
代表日期,LocalTime
表示时刻,类似11:23
这样的时刻。 LocalDateTime
就是前面2个的结合,这个可以从java.time.LocalDateTime#toString
的代码看出一二:
@Override
public String toString() {
return date.toString() + 'T' + time.toString();
}
date,time 在java.time.LocalDateTime
中
/**
* The date part.
*/
private final LocalDate date;
/**
* The time part.
*/
private final LocalTime time;
实际使用中,计算日期就用LocalDate
,计算日期加时刻用LocalDateTime
,如果只有时刻就是LocalTime
(感觉在说废话)这三个的用法基本上一样,通过方法名就知道用法那种
1.1 获取当前时间的对象
LocalDateTime localDateTime = LocalDateTime.now();
Date date = new Date();
localDateTime
相比Date
更像是一个工具类,就是为了时间操作使用。其构造方法是私有的。
1.2 从字符串中解析
字符串 2019-01-11
解析成时间对象
String str = "2019-01-11";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(str, formatter);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = simpleDateFormat.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
DateTimeFormatter
的包路径是java.time.format
和LocalDate
一样在java.time
下面,而SimpleDateFormat
和Date
是不同的。所以当判断引入路径的时候更容易判断。
当解析失败的时候,两个异常的抛出不一样,DateTimeFormatter
抛出的是DateTimeParseException
,继承自RuntimeException
,而