Java8以前,咱們想要肯定一個方法的運行時間長度,能夠這樣:java
long start = System.currentTimeMillis(); doSomething(); long end = System.currentTimeMillis(); System.out.println(end-start);
Java8中,能夠這樣
spa
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);
能夠輕鬆選擇用納秒、毫秒、秒、分鐘、小時或者天來表示時間間隔的單位。code
能夠這樣來比較第一個方法是否是比第二個執行得更快:
orm
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);
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);
//按照內置的不一樣方式格式化 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);