Java8 将小时数添加到 LocalDateTime 不起作用

Java8 Adding Hours To LocalDateTime Not Working

我试过如下,但在这两种情况下它同时显示?我做错了什么。

    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" 显示的时间与 "After 12 Hours"...

相同

LocalDateTime 的文档指定 LocalDateTime 的实例是不可变的,例如 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

所以,你在执行加操作的时候新建了一个LocalDateTime的实例,你需要给这个值赋值如下:

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

希望对您有所帮助

来自 java.time package Javadoc(强调我的):

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.

由于 java.time 包中的每个 class 都是不可变的,因此您需要捕获结果:

LocalDateTime after = currentTime.plusHours(12);
...