36. Working with dates and the java.time API

Manipulating dates and times is a common need in many Java applications. Since the release of Java 8, the java.time API has become the standard choice for working with dates and times in a simpler and less error-prone way. This API was inspired by the Joda-Time library and is known for its immutable and fluent design. Let's explore the main aspects of this API and how you can use it to perform complex date operations.

Introduction to the java.time

API

The java.time API includes a series of classes designed to deal with time concepts such as instants, durations, dates, times, time zones, and periods. Classes are immutable and thread-safe, which means you can use them without worries in multi-threaded environments.

Fundamental Classes

  • LocalDate: Represents a date without time or time zone (e.g. 2023-03-15).
  • LocalTime: Represents a time without date or time zone (e.g. 10:15:30).
  • LocalDateTime: Combines LocalDate and LocalTime, representing a date and time without a time zone.
  • ZonedDateTime: Represents a date and time complete with time zone.
  • Instant: Represents a specific point in time, generally used to mark events in applications.
  • Duration: Represents an amount of time in terms of seconds and nanoseconds.
  • Period: Represents an amount of time in terms of years, months and days.

Date Manipulation

Date manipulation is facilitated by the LocalDate, LocalTime, and LocalDateTime classes. You can create instances of these classes using their static factory methods, such as now(), of(), and parse(). Once you have an instance, you can modify its properties using methods like plusDays(), minusWeeks(), withYear(), etc. others.


LocalDate date = LocalDate.now();
LocalDate tomorrow = date.plusDays(1);
LocalDate lastMonthSameDay = date.minusMonths(1);
LocalDate in2025 = date.withYear(2025);

Formatting and Analyzing Dates

Date formatting and analysis are mainly performed by the DateTimeFormatter class. You can use predefined formatters or create your own to represent dates and times according to your needs.


DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = date.format(formatter); // "03/15/2023"
LocalDate dateFromString = LocalDate.parse("15/03/2023", formatter);

Working with Time Zones

The ZonedDateTime class is used to handle dates and times in different time zones. You can convert a LocalDateTime to a ZonedDateTime by applying a specific time zone using the atZone() method. It is also possible to adjust a ZonedDateTime to another time zone with the withZoneSameInstant() method.


ZoneId newYorkZoneId = ZoneId.of("America/New_York");
ZonedDateTime zonedDateTime = LocalDateTime.now().atZone(newYorkZoneId);
ZonedDateTime zonedDateTimeInTokyo = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));

Comparing Dates and Times

Comparing dates and times is a common operation, and the java.time API offers methods such as isBefore(), isAfter() and isEqual() to facilitate these comparisons.


boolean isAfter = tomorrow.isAfter(date);
boolean isBefore = lastMonthSameDay.isBefore(date);
boolean isEqual = in2025.isEqual(date.withYear(2025));

Time Intervals

The Duration and Period classes allow you to represent and manipulate time intervals. Duration is used for amounts of time in hours, minutes, seconds, and nanoseconds, while Period is used for days, months, and years.


Duration duration = Duration.between(LocalTime.NOON, LocalTime.MIDNIGHT);
Period period = Period.between(LocalDate.of(2023, Month.JANUARY, 1), LocalDate.of(2023, Month.DECEMBER, 31));

Temporal Adjustment API

The java.time API also includes temporal adjusters that allow you to perform complex operations in a concise way. For example, you can find the first day of the next month, the next business day, or the last day of the year using temporal adjusters.


LocalDate firstDayOfNextMonth = date.with(TemporalAdjusters.firstDayOfNextMonth());
LocalDate nextWednesday = date.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
LocalDate lastDayOfYear = date.with(TemporalAdjusters.lastDayOfYear());

Conclusion

The java.time API is a powerful and flexible tool for working with dates and times in Java. With its immutable and thread-safe design, it provides a reliable and efficient way to handle complex temporal concepts in your applications. By mastering this API, you will be able to handle any date and time related challenge with ease.

Now answer the exercise about the content:

Which of the following statements about the `java.time` API is true?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Internationalization and Localization in Java

Next page of the Free Ebook:

148Internationalization and Localization in Java

5 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text