java8对原来的时间API进行了规范
获取时间: 创建对象的方式都是静态方法
1、LocalDte LocalTime LocalDateTime 人看的
LocalDateTime now = LocalDateTime.now();
LocalDateTime localDateTime = now.plusDays(20);
System.out.println(localDateTime);
LocalDateTime dateTime = LocalDateTime.of(2015, 2, 12, 1, 2);
System.out.println(dateTime);
2、Instant 时间戳 Unix元年 开始算的毫秒值
Instant instant = Instant.now();
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(instant+"\t:\t"+offsetDateTime);
3、Duration: 计算两个“时间”之间的间隔
Instant ins1 = Instant.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant ins2 = Instant.now();
System.out.println(Duration.between(ins1,ins2).toMillis());
4、 Period 计算两个 日期 的间隔
LocalDate of1 = LocalDate.of(2015, 1, 1);
LocalDate of2 = LocalDate.of(2015, 10, 1);
System.out.println(Period.between(of1,of2).getMonths());
5、TemporalAdjuster 时间矫正器 工具类TemporalAdjusters
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(3);
System.out.println(localDateTime1);
LocalDateTime with = localDateTime.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(with);
localDateTime.with((l)->{
LocalDateTime ld4 = (LocalDateTime)l;
DayOfWeek dayOfWeek = ld4.getDayOfWeek();
if(dayOfWeek.equals(DayOfWeek.SATURDAY)){
return ld4.plusDays(1);
}
return ld4.plusDays(5);
});
6、DateTimeFormatter 时间格式化
DateTimeFormatter ldf = DateTimeFormatter.ISO_DATE;
LocalDateTime now = LocalDateTime.now();
String format = now.format(ldf);
System.out.println(format);
DateTimeFormatter ldf1 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String format1 = now.format(ldf1);
System.out.println(format1);
LocalDateTime parse = now.parse(format1, ldf1);
System.out.println(parse);
7、 时区的处理
LocalDateTime.now(ZoneId.of("Asia/Shanghai)) ;
8、格式化为日期
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
Callable<LocalDate> task = new Callable<LocalDate>() {
@Override
public LocalDate call() {
return LocalDate.parse("20161218",dtf);
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<LocalDate>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futures.add(pool.submit(task));
}
for(Future<LocalDate> future :futures){
System.out.println(future.get());
}
}
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){
protected DateFormat initialValue(){
return new SimpleDateFormat("yyyyMMdd");
}
};
public static Date conver(String source) throws ParseException {
return df.get().parse(source);
}