AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Introduction to Java 8 dates

The treatment of Java dates and times has been greatly simplified after Java 8, so in this post we are going to see an Introduction to Java 8 Dates. This helps developers avoid more complex tasks and reduces the need for third-party libraries.

Some of the improvements that have been introduced are:

  • Thread Safety: The Date and Calendar objects were not thread-safe. To address this issue, the new API is immutable and thread-safe.
  • Improved API Design: The old date API was more complicated and challenging to use. In this version, the understanding has been improved, and its usage has been made easier.
  • TimeZone: The new API simplifies the usage of TimeZone.

Use of LocalDate, LocalDateTime, and LocalTime

These are the most commonly used classes in any project. LocalDate represents a date without time, LocalTime represents a time, and LocalDateTime provides both date and time. They display the date and time in our local time zone.

Let’s look at a few examples:

LocalDate currentDay = LocalDate.now(); (1)
LocalTime currentTime = LocalTime.now();actual (2)
LocalDateTime currentDateAndTime = LocalDateTime.now();  (3)

In the above example:

  • (1) Represents the date at the current moment.
  • (2) Represents the time at the current moment.
  • (3) Represents the date and time at the current moment.

What if we want a specific date and time?

LocalDate day = LocalDate.of(2020,3,3); (1)
LocalTime time = LocalTime.of(6,30); (2)
LocalDateTime dateAndTime = LocalDateTime.now(2020,3,3,6,30);  (3)

In the previous example:

  • (1) Represents the date as March 3, 2020.
  • (2) Represents the time as 6:30.
  • (3) Represents the date and time as March 3, 2020, at 6:30.

Converting from LocalDateTime to LocalDate and LocalTime:

LocalDateTime dateAndTime = LocalDateTime.now(2020,3,3,6,30);  
LocalDate localDate = dateAndTime.toLocalDate();
LocalTime localTime = dateAndTime.toLocalTime();

We can also use a DateTimeFormatter.ISO_LOCAL_DATE_TIME as follows:

LocalDateTime dateTime = LocalDateTime.parse("2020-01-10T06:30");

So far, we have seen that the usage of this API is quite straightforward. Let’s explore incrementing or decrementing hours and days:

LocalDate date = LocalDate.now().minusDays(1L);
LocalDate date2 = LocalDate.now().plusDays(1L);
LocalDate date3 = LocalDate.now().plusDays(2L, ChronoUnit.Days);

LocalTime time1 = LocalTime.now().plusMinutes(1L);
LocalTime time2 = LocalTime.now().minusMinutes(2L);
LocalTime time3 = LocalTime.now().plusMinutes(2L, ChronoUnit.Minutes);

Now let’s go back to the old date format with Date() and vice versa, and perform conversions. Although LocalDate, LocalTime, and LocalDateTime do not contain any information about Zone or Offset, as we are going to use Instant, we need to provide an offset.

Date now = new Date(); // fecha 1 de Abril 2 semanas de confinamiento
LocalDateTime currentDate = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()); 

Date date = Date.from(currentDate.toInstant(ZoneOffset.ofHours(1)));
Date date = Date.from(currentDate.toInstant(ZoneId.systemDefault().getRules().getOffset(currentDate)));

Working with Duration and Period

Both Duration and Period are representations of time between two dates.

Example with Period, used to get the time between two LocalDate objects:

LocalDate firstDayOfQuarantine = LocalDate.parse("2020-03-15");
LocalDate lastDayOfQuarantine = LocalDate.parse("2020-04-14");
int totalDaysOfQuarantine = Period.between(firstDayOfQuarantine, lastDayOfQuarantine).getDays();

Example with Duration, which is commonly used to get the time between LocalTime objects:

LocalTime currentTime = LocalTime.now();
LocalTime finalTime = LocalTime.now().plusMinutes(5L);
long total = Duration.between(currentTime, finalTime).getSeconds();

Working with ZoneDateTime and OffsetDateTime

Java 8 introduced the ZoneDateTime class for working with specific time zones. There are around 40 different zones, and thanks to ZoneId, we can select a zone.

ZoneId zoneId = ZoneId.of("Europe/Paris");

Converting a time to a specific zone:

LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);

We can also use a parser:

ZonedDateTime.parse("2020-04-01T12:15:30+01:00[Europe/Paris]");

We can also use OffsetDateTime to work with zones. OffsetDateTime is an immutable representation of a date-time object with an offset.

LocalDateTime localDateTime = LocalDateTime.now();

Now let’s add 3 hours by creating a ZoneOffset:

ZoneOffset zoneOffset = ZoneOffset.of("+03:00");
OffsetDateTime offsetDateTime = OffsetDateTime.of(localDateTime, zoneOffset);

After this, we would have a LocalDateTime of 2020-04-01 20:01 +3:00.

Using formatters for dates

Since different date formats are used around the world, it becomes necessary to use formatters. In the following example, we will test various formats:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy-MM-dd][dd/MM/yyyy][MM-dd-yyyy]");
LocalDate.parse("04-04-2020", formatter);
LocalDate.parse("04/04/2028", formatter);
LocalDate.parse("2020-04-04", formatter);

By defining formatters in the above way, we can use the formatter based on what we want to parse.

Can we format only a specific part? Yes, like this:

<br>DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-[MM-dd][MMM-dd]" );
LocalDate.parse( "2020-04-04", formatter );
LocalDate.parse( "2018-Apr-04", formatter );

Conclusion of Java Dates and Times after Java 8

We have seen an introduction to Java 8 Dates. This dates format facilitate the developer’s work.

If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!

Leave a Reply

Your email address will not be published. Required fields are marked *