Working with LocalDateTime

Jumping to JDK 8, the focus is on LocalDate, LocalTime, LocalDateTime, Instant, and many more. The new Java date-time API comes with methods that are dedicated to adding or subtracting an amount of time. LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, Instant, Period, Duration, and many others come with methods such as plusFoo() and minusFoo(), where Foo can be replaced with the unit of time (for example, plusYears(), plusMinutes(), minusHours(), minusSeconds(), and so on).

Let's assume the following LocalDateTime:

// 2019-02-25T14:55:06.651155500
LocalDateTime ldt = LocalDateTime.now();

Adding 10 minutes is as easy as calling LocalDateTime.plusMinutes(long minutes), while subtracting 10 minutes is as easy as calling LocalDateTime.minusMinutes(long minutes):

LocalDateTime ldtAfterAddingMinutes = ldt.plusMinutes(10);
LocalDateTime ldtAfterSubtractingMinutes = ldt.minusMinutes(10);

The output will reveal the following dates:

After adding 10 minutes: 2019-02-25T15:05:06.651155500
After subtracting 10 minutes: 2019-02-25T14:45:06.651155500
Beside the methods dedicated per time unit, these classes also support plus/minus(TemporalAmount amountToAdd)  and  plus/minus(long amountToAdd, TemporalUnit unit).

Now, let's focus on the Instant class. Besides plus/minusSeconds(), plus/minusMillis(), and plus/minusNanos(), the Instant class also provides a  plus/minus(TemporalAmount amountToAdd) method.

In order to exemplify this method, let's assume the following Instant:

// 2019-02-25T12:55:06.654155700Z
Instant timestamp = Instant.now();

Now, let's add and subtract 5 hours:

Instant timestampAfterAddingHours 
= timestamp.plus(5, ChronoUnit.HOURS);
Instant timestampAfterSubtractingHours
= timestamp.minus(5, ChronoUnit.HOURS);

The output will reveal the following Instant:

After adding 5 hours: 2019-02-25T17:55:06.654155700Z
After subtracting 5 hours: 2019-02-25T07:55:06.654155700Z
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset