Java 8 introduced new APIs for Date and Time to address the shortcomings of the older
1. Java 8 Date Time API Packages
Java 8 Date Time API consists of following packages.
- java.time This is the base package of new Java Date Time API. All the major base classes are part of this package, such as
LocalDate ,LocalTime ,LocalDateTime ,Instant ,Period ,Duration etc. All of these classes are immutable and thread safe. Most of the times, these classes will be sufficient for handling common requirements. - java.time.chrono This package defines generic APIs for non ISO calendar systems. We can extend
AbstractChronology class to create our own calendar system. - java.time.format This package contains classes used for formatting and parsing date time objects. Most of the times, we would not be directly using them because principle classes in
java.time package provide formatting and parsing methods. - java.time.temporal This package contains temporal objects and we can use it for find out specific date or time related to date/time object. For example, we can use these to find out the first or last day of the month. You can identify these methods easily because they always have format “withXXX”.
- java.time.zone This package contains classes for supporting different time zones and their rules.
Please note that this post is mainly driven by code examples that show the new API functionality. We think the examples are self-explanatory.
2. Using LocalDate, LocalTime and LocalDateTime API
-
Exploring LocalDate
LocalDate represents a date in ISO format (yyyy-MM-dd) without time.
0123456789101112131415161718192021222324252627282930313233// the current date in format yyyy-MM-ddLocalDate currentDate = LocalDate.now();// 2016-02-29LocalDate formattedDate = LocalDate.of(2016, Month.FEBRUARY, 29);// the 75th day of 2016 (2016-03-15)LocalDate dayFromNumber = LocalDate.ofYearDay(2016, 75);// parse date from stringLocalDate parseDateFromString = LocalDate.parse("2016-08-08");// today + 1 day = tomorrowLocalDate tomorrow = LocalDate.now().plusDays(1);// same day of previous monthLocalDate previousMonthSameDay = LocalDate.now().minus(1, ChronoUnit.MONTHS);// day of specific dateDayOfWeek friday = LocalDate.parse("2016-08-12").getDayOfWeek();// day of month for specific dateint twelve = LocalDate.parse("2016-08-12").getDayOfMonth();// Is leap year?boolean leapYear = LocalDate.now().isLeapYear();// date on left side is before date on right side?boolean isBefore = LocalDate.parse("2016-08-15").isBefore(LocalDate.parse("2016-08-20"));// first day of the month for specific dateLocalDate firstDayOfMonth = LocalDate.parse("2016-08-28").with(TemporalAdjusters.firstDayOfMonth()); -
Exploring LocalTime
LocalTime represents time without a date.
0123456789101112131415161718192021222324252627282930// current time in format HH:mm:ss.SSSLocalTime currentTime = LocalTime.now();// 10:10 in 24hr formatLocalTime timeFromNumber = LocalTime.of(10, 10);// 20000th second of day (03:25:45)LocalTime fromSecondsOfDay = LocalTime.ofSecondOfDay(20000);// parse time from stringLocalTime parseTime = LocalTime.parse("10:10");// add 1hr to current timeLocalTime nextHour = LocalTime.now().plusHours(1);// minus 2hrs from current timeLocalTime backToTwoHours = LocalTime.now().minus(2, ChronoUnit.HOURS);// minutes from timeint minutesFromTime = LocalTime.parse("10:10").getMinute();// time on left side is before time on right side?boolean isbefore = LocalTime.parse("10:10").isBefore(LocalTime.parse("11:05"));// current (local) time in IndiaLocalTime currentTimeInIndia = LocalTime.now(ZoneId.of("Asia/Kolkata"));// Current time in UTC time zoneLocalTime nowInUtc = LocalTime.now(Clock.systemUTC()); -
Exploring LocalDateTime
LocalDateTime is used to represent a combination of date and time.
An instance of
LocalDateTime can be obtained from the system clock similar toLocalDate andLocalTime 0123456789101112131415161718192021// the current date in format yyyy-MM-ddLocalDateTime currentDate = LocalDateTime.now();// 2016-08-08T10:10LocalDateTime dateFromNumbers = LocalDateTime.of(2016, 8, 8, 10, 10);// 2016-08-08T10:10LocalDateTime dateFromNumbers1 = LocalDateTime.of(2016, Month.AUGUST, 8, 10, 10);// parse date-time from stringLocalDateTime parseDateTime = LocalDateTime.parse("2016-08-08T10:10");// add one day in specific timeLocalDateTime addDays = LocalDateTime.now().plusDays(1);// minus five hours in specific timeLocalDateTime minusHours = LocalDateTime.now().minusHours(5);// get month of specific dateMonth currentMonth = LocalDateTime.now().getMonth();

3. Using ZonedDateTime API
We can use
There are about 40 different time zones provided by
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Zone for India ZoneId asiaIndia = ZoneId.of("Asia/Kolkata"); // All available zones Set<String> allZoneIds = ZoneId.getAvailableZoneIds(); // Convert a specific time in the given time zone ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.now(), asiaIndia); // parse zoned date time ZonedDateTime.parse("2017-08-22T16:00:22.234+05:30[Asia/Kolkata]"); // add three hours to the zoned time ZoneOffset offset = ZoneOffset.of("+03:00"); // add offset to the specific date-time OffsetDateTime offSetByTwo = OffsetDateTime.of(LocalDateTime.now(), offset); |
4. Using Instant API a.k.a Timestamps
An Instant counts the time beginning from the first second of January 1, 1970 (1970-01-01 00:00:00) also called the EPOCH.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// current timestamps Instant now = Instant.now(); // from unix timestamp, 2016-08-08T10:44:18Z Instant fromUnixTimestamp = Instant.ofEpochSecond(1470653058); // same time in millis Instant fromEpochMilli = Instant.ofEpochMilli(1470653058000l); // parsing from ISO 8601 Instant fromIso8601 = Instant.parse("2016-08-08T12:00:00Z"); // as unix timestamp long toUnixTimestamp = now.getEpochSecond(); // in millis long toEpochMillis = now.toEpochMilli(); // plus/minus methods are available too Instant nowPlusTenSeconds = now.plusSeconds(10); |
5. Using Period and Duration
The Period class represents a quantity of time in terms of years, months and days and the Duration class represents a quantity of time in terms of seconds and nano seconds.
-
Exploring Period
01234567891011121314LocalDate firstDate = LocalDate.of(2012, 8, 8); // 2012-08-08LocalDate secondDate = LocalDate.of(2016, 2, 21); // 2016-02-21// get difference between two datesPeriod period = Period.between(firstDate, secondDate);int days = period.getDays(); // 13int months = period.getMonths(); // 6int years = period.getYears(); // 3boolean isNegative = period.isNegative(); // false// selects 2 months and 15 daysPeriod specificPeriods = Period.ofMonths(2).plusDays(15); -
Exploring Duration
0123456789101112131415Instant firstInstant= Instant.ofEpochSecond( 1470654323 ); // 2016-08-08 11:05Instant secondInstant = Instant.ofEpochSecond(1470687623); // 2011-01-11 20:20// get difference between two timeDuration between = Duration.between(firstInstant, secondInstant);// negative because firstInstant is after secondInstant (33300)long seconds = between.getSeconds();// get absolute result in minutes (555)long absoluteResult = between.abs().toMinutes();// four hours in seconds (14400)long fourHoursInSeconds = Duration.ofHours(4).getSeconds();
6. Date and Time Formatting
Java 8 provides APIs for the easy formatting of Date and Time.
0 1 2 3 4 5 6 7 8 9 10 11 |
LocalDateTime localDateTime = LocalDateTime.of(2016, Month.AUGUST, 8, 10, 10); // format in ISO date format - yyyy-MM-dd String localDate = localDateTime.format(DateTimeFormatter.ISO_DATE); // in specific format - dd/MM/yyyy String formattedDate = localDateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); // in specific format - Aug 8, 2016 10:10:00 AM String formattedDate1 = localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.US)); |
7. Conclusion
Java 8 provides a rich set of APIs with a consistent API design for easier development. The API can completely replace old classes like