New Date Time API

The new date api tries to fix the java8 below version problems with legacy classes. It contains mainly the following classes:

  1. java.time.LocalDate : represents a year-month-day in the ISO calendar and is useful for representing a date without a time. It can be used to represent a date only information such as a birth date or wedding date.
  2. java.time.LocalTime : deals in time only. It is useful for representing human-based time of day, such as movie times, or the opening and closing times of the local library.
  3. java.time.LocalDateTime : handles both date and time, without a time zone. It is a combination of LocalDate with LocalTime.
  4. java.time.ZonedDateTime : combines the LocalDateTime class with the zone information given in ZoneId class. It represent a complete date time stamp along with timezone information.
  5. java.time.OffsetTime : handles time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  6. java.time.OffsetDateTime : handles a date and time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  7. java.time.Clock : provides access to the current instant, date and time in any given time-zone. Although the use of the Clock class is optional, this feature allows us to test your code for other time zones, or by using a fixed clock, where time does not change.
  8. java.time.Instant : represents the start of a nanosecond on the timeline (since EPOCH) and useful for generating a timestamp to represent machine time. An instant that occurs before the epoch has a negative value, and an instant that occurs after the epoch has a positive value.
  9. java.time.Duration : Differnce between two instants and measured in seconds or nanoseconds and does not use date-based constructs such as years, months, and days, though the class provides methods that convert to days, hours, and minutes.
  10. java.time.Period : To define the difference between dates in date-based values (years, months, days).
  11. java.time.ZoneId : specifies a time zone identifier and provides rules for converting between an Instant and a LocalDateTime.
  12. java.time.ZoneOffset : specifies a time zone offset from Greenwich/UTC time.
  13. java.time.format.DateTimeFormatter : provides numerous predefined formatters, or we can define our own. It provides parse() or format() method to parsing and formatting the date time values.
  14. TemporalAdjusters: provide many useful inbuilt adjusters for handling recurring events.
  15. TemporalQuery: be used as the assignment target for a lambda expression or method reference.
  16. DayOfWeek: an enum representing the seven days of the week – Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
1. Get Current Date and Time

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
                      
                    

2. Parse Date and Time

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
                      
                    

3. Format Date and Time

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
                      
                    

4. Measure Elapsed Time

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
                      
                    

5. Calculate Days between Two Dates

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);