Java8中新增的日期和时间API
cfn5
9年前
本文记录了一些Java8中新增的日期和时间API的基本用法
1.计算时间间隔
Java8之前,我们想要确定一个方法的运行时间长度,可以这样:
long start = System.currentTimeMillis(); doSomething(); long end = System.currentTimeMillis(); System.out.println(end-start);
Java8中,可以这样
Instant start = Instant.now(); doSomething(); Instant end = Instant.now(); Duration time = Duration.between(start, end); long seconds = time.getSeconds();//秒表示 long millis = time.toMillis();//毫秒表示 System.out.println(seconds); System.out.println(millis);
可以轻松选择用纳秒、毫秒、秒、分钟、小时或者天来表示时间间隔的单位。
可以这样来比较第一个方法是不是比第二个执行得更快:
Instant start = Instant.now(); doSomething(); Instant end = Instant.now(); Duration time = Duration.between(start, end); Instant start2 = Instant.now(); doSomething2(); Instant end2 = Instant.now(); Duration time2 = Duration.between(start2, end2); boolean fast = time.minus(time2).isNegative(); System.out.println(fast);
2.本地日期和时间
LocalDate now = LocalDate.now(); LocalDate date = LocalDate.of(2005, 5, 10); LocalDate date2 = LocalDate.of(2003, Month.FEBRUARY, 5); System.out.println(now); System.out.println(date); System.out.println(date2); LocalTime now2 = LocalTime.now(); LocalTime time = LocalTime.of(22, 50, 56); System.out.println(now2); System.out.println(time);
3.日期格式化
//按照内置的不同方式格式化 String format = DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now()); String format2 = DateTimeFormatter.ISO_LOCAL_TIME.format(LocalTime.now()); String format3 = DateTimeFormatter.ISO_DATE.format(LocalDateTime.now()); String format4 = DateTimeFormatter.ISO_INSTANT.format(Instant.now()); System.out.println(format); System.out.println(format2); System.out.println(format3); System.out.println(format4); //按照标准格式格式化 DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL); String format5 = formatter.format(LocalDateTime.now()); System.out.println(format5); //按照指定方式格式化 DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd E HH:mm:ss"); String format6 = pattern.format(LocalDateTime.now()); System.out.println(format6);