- Period is a date-based representation of time in Days, Month and Years and is part of the java.time package.
- Compatible with LocalDate.
- It represents a Period of time not just a specific date and time.
Example:
Period period1 = Period.ofDays(10); // represents a Period of 10 days
Period period2 = Period.ofYears(20); // represents a Period of 20 years
- Mainly used to calculate the difference between the two dates.
Example:
LocalDate localDate1 = LocalDate.of(2018, 01, 01);
LocalDate localDate2 = LocalDate.of(2018, 01, 31);
Period period = Period.**between**(locaDate1, localDate2); // calculates the difference between the two dates
- A time based representation of time in hours, minutes, seconds and nanoseconds
- Compatible with LocalTime and LocalDateTime
- It represents a duration of time not just a specific time.
Example:
Duration duration1 = Duration.ofHours(3); // represents the duration of 3 hours
Duration duration1 = Duration.ofMinutes(3); // represents the duration of 3 minutes
- It can be used to calculate the difference between the time objects such as LocalTime and LocalDateTime.
Example:
LocalTime localTime = LocalTime.of(7, 20);LocalTime localTime1 = LocalTime.of(8, 20);long diff = localTime.until(localTime1, ChronoUnit.MINUTES);System.out.println("Difference in minutes :: " + diff);
- Represents the time in a machine-readable format.
Example
Instant instant = Instant.now();
- Represents the time in seconds from January 1st, 1970, (EPOCH) to current time as a huge number.
- ZonedDateTime, ZoneId, ZoneOffset
- ZonedDateTime - represents the date/time with its time zone. Example: 2018-07-18T08:04:14.541-05:00[America/Chicago]
ZoneOffset -> -05:00 ZoneId -> America/Chicago
- Introduced in Java 8 and part of the java.time.format package.
- Used to parse and format the LocalDate, LocalTime and LocalDateTime.
- parse - Converting a String to a LocalDate/LocalTime/LocalDateTime.
- format - Converting a LocalDate/LocalTime/LocalDateTime to a string.
See https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html