The new date api tries to fix the java8 below version problems with legacy classes. It contains mainly the following classes:
All date-time classes have a factory method now() which is the preferred way to get the current date and time in Java 8.
LocalTime currentTime = LocalTime.now(); //13:33:43.557
LocalDate currentDate = LocalDate.now(); //2020-05-03
LocalDateTime currentDateTime = LocalDateTime.now(); //2020-05-03T13:33:43.557
Date parsing is done with the help of DateTimeFormatter class and parse() methods in date-time classes.
String dateString = "2020-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime parsedDateTime = LocalDateTime.parse(dateString, formatter);
System.out.println(parsedDateTime); //2020-04-08T12:30
Date formatting is done with the help of DateTimeFormatter class and format() methods in date-time classes.
//Format a date
LocalDateTime myDateObj = LocalDateTime.now();
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String formattedDate = myDateObj.format(myFormatObj);
System.out.println(formattedDate); // 03-05-2020 13:46
To get the elapsed execution time in different time units, use methods such as toDays(), toHours(), toMillis(), toMinutes(), toNanos() and getSeconds() from the java.time.Instant and java.time.Duration classes.
Instant start = Instant.now();
//Measure execution time for this method
methodToMeasureExecutionTime();
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis(); //in millis
To calculate number of days between two dates in Java 8 using ChronoUnit.DAYS.between() and LocalDate.until() methods.
LocalDate date1 = LocalDate.now();
LocalDate date2 = date1.plusDays(99);
long diffInDays = ChronoUnit.DAYS.between(date1, date2);