Java8 Adding Hours To LocalDateTime Not Working
Asked Answered
H

3

31

I tried like below, but in both cases, it is showing the same time. What am I doing wrong?

LocalDateTime currentTime = LocalDateTime.now(ZoneId.of("UTC"));
Instant instant = currentTime.toInstant(ZoneOffset.UTC);
Date currentDate = Date.from(instant);
System.out.println("Current Date = " + currentDate);

currentTime.plusHours(12);
Instant instant2 = currentTime.toInstant(ZoneOffset.UTC);
Date expiryDate = Date.from(instant2);
System.out.println("After 12 Hours = " + expiryDate);

"Current Date" Time is showing the same as "After 12 Hours"...

Hibernal answered 23/6, 2015 at 13:4 Comment(0)
D
52

The documentation of LocalDateTime specifies the instance of LocalDateTime is immutable, for example plusHours

public LocalDateTime plusHours(long hours)

Returns a copy of this LocalDateTime with the specified number of hours added.

This instance is immutable and unaffected by this method call.

Parameters:
hours - the hours to add, may be negative
Returns:
a LocalDateTime based on this date-time with the hours added, not null
Throws:
DateTimeException - if the result exceeds the supported date range

So, you create a new instance of LocalDateTime when you execute plus operation, you need to assign this value as follows:

LocalDateTime nextTime = currentTime.plusHours(12);
Instant instant2 = nextTime.toInstant(ZoneOffset.UTC);
Date expiryDate = Date.from(instant2);
System.out.println("After 12 Hours = " + expiryDate);

I hope it can be helpful for you.

Diggs answered 23/6, 2015 at 13:28 Comment(1)
Damn, i missed the immutable part. It works now. Thank You Very Much.Hibernal
P
11

From the java.time package Javadoc (emphasis mine):

The classes defined here represent the principal date-time concepts, including instants, durations, dates, times, time-zones and periods. They are based on the ISO calendar system, which is the de facto world calendar following the proleptic Gregorian rules. All the classes are immutable and thread-safe.

Since every class in the java.time package is immutable, you need to capture the result:

LocalDateTime after = currentTime.plusHours(12);
...
Pyx answered 23/6, 2015 at 14:6 Comment(0)
M
0

This is simple, you can use

LocalDateTime's method "plusHours(numberOfHours)

Like This

localDateTime.plusHours(numberOfHours);
Miyasawa answered 1/11, 2022 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.