新时间API
简介
之前时间API存在线程安全问题,设计混乱,顾重新编写的新时间类
验证:
SimpleDateFormat sdf=newSimpleDateFormat("yyyyMMdd");
ExecutorService pool = Executors.newFixedThreadPool(10);
Callable callable=new Callable() {
@Override
public Date call() throws Exception {
return sdf.parse("20200525");
}
};
List> list=new ArrayList<>();
for(int i=0;i<10;i++) {
Future future=pool.submit(callable);
list.add(future);
}
for (Future future : list) {
System.out.println(future.get().toLocaleString());
}
pool.shutdown();
会崩溃
新时间相关类
LocalDate
LocalDateTime
作用:代替Date
方法:
now():获取当前时间,静态方法
of():获取指定时间,静态方法
getYear():获取年
getMonthValue():获取月
getDayOfMonth():获取日
plusXXX():添加
minusXXX():减少
atZone(ZoneId zoneId):将时间转换为指定时区的时间
format(DateTimeFormatter dtf):将时间转换为指定格式的字符串
parse(CharSequence text, DateTimeFormatter formatter):将指定格式的字符串转换为时间
代码:
//1创建本地时间
LocalDateTime localDateTime=LocalDateTime.now();
//LocalDateTime localDateTime2=LocalDateTime.of(year, month, dayOfMonth,
hour, minute)
System.out.println(localDateTime);
System.out.println(localDateTime.getYear());
System.out.println(localDateTime.getMonthValue());
System.out.println(localDateTime.getDayOfMonth());
//2添加两天
LocalDateTime localDateTime2 = localDateTime.plusDays(2);
System.out.println(localDateTime2);
//3减少一个月
LocalDateTime localDateTime3 = localDateTime.minusMonths(1);
System.out.println(localDateTime3);
DateTimeFormatter
作用:代替SimpleDateFormat
方法:
ofPattern("时间格式"):设定时间格式
代码:
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyyMMdd");
ExecutorService pool = Executors.newFixedThreadPool(10);
Callable callable=new Callable() {
@Override
public LocalDate call() throws Exception {
return LocalDate.parse("20200525",dtf);
}
};
List> list=new ArrayList<>();
for(int i=0;i<10;i++) {
Future future=pool.submit(callable);
list.add(future);
}
for (Future future : list) {
System.out.println(future.get());
}
pool.shutdown();
Instant:时间戳
方法:
public static Instant now():获取当前时间
public long toEpochMilli():获取当前时间与1970年1月1日00:00:00:000的时间差,单位
毫秒
public Instant plusSeconds(long secondsToAdd):减数当前时间的秒数
ZoneId:时区
方法:
public static Set getAvailableZoneIds():获取所有时区
public static ZoneId systemDefault():获取系统默认时区
时间转换:
Date --->Instant---->LocalDateTime
代码:
Date date=new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant,
ZoneId.systemDefault());
LocalDateTime —>Instant---->Date
代码:
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date from = Date.from(instant);
System.out.println(from);