摘抄如下
背景
在JDK1.7中,处理日期相关的数据我们使用java.util.Data和calendar.当使用他存储日期或者只存储时间,那么只有定义的人才知道哪些数据是有用的。而且在java.util.Date中的月份从0开始,一月是0,十二月是11。计算月份时往往会出错.Date类直接打印效果为”Fri Dec 13 09:23:03 CST 2019”不适于阅读.SimpleDateFormat不是线程安全,只能在方法内部使用.
在JDK1.8及以后的API中,对于时间的使用我们更加便利。新增了LocalDate、LocalTime、LocalDateTime,分别表示ISO-8601日历系统(国际标准化组织制定的现代公民的日期和时间的表示法)的日期,时间、日期和时间。他们提供简单的日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。并且他们类的实例是不可变的对象,不但线程安全,而且不能修改。
内容
LocalDate日期处理类
LocalTime时间处理类
LocalDateTime日期时间处理类
LocalDate无法包含时间,LocalTime无法包含日期。当然,LocalDateTime才能同时包含日期和时间。
static LocalTime now() 获取当前时间
static of 构造时间/日期
static LocalTime of(int year, int month , int day ) 构造时间
int getYear( ) 获取年份
int getMonthValue( ) 获取月份
int getDayOfMonth( ) 获取日
Int getMinute() 获取分钟
Int getHour() 获取小时
生成当前日期之后或之前 n 天的日期:
Local Date piusDays(int n )
Local Date minusDays(int n)
同理适用于小时,分钟等;
时间调整(with):
withYear(int);
withMonth();
withDayOfMonth();
withHour();
withMinute();
withSecond();
LocalDate localDate=LocalDate.now();
System.out.println(localDate.withYear(2020));
时间与字符串转换:
DateTimeFormatter 线程安全
SimpleDateFormat线程不安全
因为SimpleDateFormat不是线程安全的,使用的时候,只能在方法内部创建新的局部变量。而DateTimeFormatter可以只创建一个实例,到处引用。
直接使用常量创建DateTimeFormatter格式器:
DateTimeFormatter.ISO_LOCAL_DATE 日期
DateTimeFormatter.ISO_LOCAL_TIME 时间
DateTimeFormatter.ISO_LOCAL_DATE_TIME 日期+时间
DateTimeFormatter xy=DateTimeFormatter.ISO_LOCAL_TIME
也可以手动创建格式:
DateTimeFormatter xx=DateTimeFormatter.ofPattern("MM");
时间转字符串
DateTimeFormatter xx=DateTimeFormatter.ISO_DATE;
String zifuchuan=localDate.format(xx);
字符串转时间
LocalDate date2=LocalDate.parse(zifuchuan);
Duration表示两个时刻之间的时间间隔。另一个类似的Period表示两个日期之间的天数.
Instant时间戳
打印秒/毫秒.
Instant now=Instant.now();
System.out.println(now.getEpochSecond());
System.out.println(now.toEpochMilli());