Java8为LocalDateTime添加时间不起作用 [英] Java8 Adding Hours To LocalDateTime Not Working
问题描述
我尝试过如下,但在两种情况下它都显示同一时间?我做错了。
I tried like below, but in both the cases it is showing same time? What i am 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);
当前日期时间与12小时后相同......
"Current Date" Time is showing Same as "After 12 Hours"...
推荐答案
LocalDateTime
的文档指定 LocalDateTime <的实例/ code>是不可变的,例如
plusHours
The documentation of LocalDateTime
specifies the instance of LocalDateTime
is immutable, for example plusHours
public LocalDateTime plusHours(长时间)
返回指定的 LocalDateTime
的副本已添加
小时数。
Returns a copy of this LocalDateTime
with the specified number of
hours added.
此实例不可变且不受此方法调用的影响。
This instance is immutable and unaffected by this method call.
参数:
小时
- 要添加的小时数,可能为负数
退货:
a LocalDateTime基于此日期时间添加小时数,而不是null
投掷:
DateTimeException - 如果结果超出支持的日期范围
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实例
执行加号操作时,需要按如下方式赋值:
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.
这篇关于Java8为LocalDateTime添加时间不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!