Java 8 Java8向LocalDateTime添加小时数不工作
我试着像下面这样,但在这两种情况下,它是显示在同一时间?我做错了什么Java 8 Java8向LocalDateTime添加小时数不工作,java-8,java-time,Java 8,Java Time,我试着像下面这样,但在这两种情况下,它是显示在同一时间?我做错了什么 LocalDateTime currentTime = LocalDateTime.now(ZoneId.of("UTC")); Instant instant = currentTime.toInstant(ZoneOffset.UTC); Date currentDate = Date.from(instant); System.out.println("Current Date = " +
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);
“当前日期”时间显示与“12小时后”相同。…例如,
LocalDateTime
的文档指定了LocalDateTime
的实例是不可变的
public LocalDateTime plusHours(长时间)
返回此LocalDateTime
的副本,其中包含指定数量的
增加了几个小时
此实例是不可变的,不受此方法调用的影响
参数:hours
-要添加的小时数可能为负数返回:
基于此日期时间并添加小时数的LocalDateTime,不为空
抛出:
DateTimeException-如果结果超出支持的日期范围 因此,在执行plus操作时,您需要创建一个新的
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
(我的重点):
此处定义的类表示主要的日期时间概念,
包括瞬间、持续时间、日期、时间、时区和时段。
它们基于ISO日历系统,这是事实上的世界
遵循公历规则的日历所有的类都是
不可变且线程安全。
由于java.time
包中的每个类都是不可变的,因此需要捕获结果:
LocalDateTime after = currentTime.plusHours(12);
...
该死,我错过了永恒的部分。现在可以了。非常感谢你。