【问题标题】:Java8 Adding Hours To LocalDateTime Not WorkingJava8向LocalDateTime添加小时不起作用
【发布时间】:2015-06-23 13:04:52
【问题描述】:

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

    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 小时后”相同...

【问题讨论】:

    标签: java-8 java-time


    【解决方案1】:

    LocalDateTime的文档指定LocalDateTime的实例是不可变的,例如plusHours

    public LocalDateTime plusHours(long hours)

    返回此LocalDateTime 的副本,其中包含指定数量的 增加了几个小时。

    此实例是不可变的,不受此方法调用的影响。

    参数:
    hours - 添加的小时数,可能为负
    返回:
    基于此日期时间的 LocalDateTime 加上小时数,不为空
    抛出:
    DateTimeException - 如果结果超出支持的日期范围

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

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

    希望对你有帮助。

    【讨论】:

    • 该死,我错过了不可变的部分。现在可以了。非常感谢。
    【解决方案2】:

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

    这里定义的类代表主要的日期时间概念, 包括瞬间、持续时间、日期、时间、时区和时期。 它们基于 ISO 日历系统,这是事实上的世界 日历遵循预测的公历规则。 所有课程都是 不可变且线程安全。

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

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

    【讨论】:

      最近更新 更多