从Java控制台上的LocalTime.of()方法更新Localtime对象

问题描述 投票:-3回答:2

如果有人可以帮助我,我在这里有一个小问题,我将非常感激!

当我尝试更新通过LocalTime方法创建的LocalTime.now()对象时,我可以看到时间在流逝,它起作用这是代码:

     public static void main(String[] args) {

        LocalTime d = LocalTime.now();
        String h = String.valueOf(d.getHour());
        String m = String.valueOf(d.getMinute());
        String s = String.valueOf(d.getSecond());
        System.out.print("\r"+h + ":" + m + ":" + s);

        //Update :
        Thread.sleep(1000);


     }

输出:

1:53:2 (time is passing)

但是当我运行这个时:

     public static void main(String[] args) {

        LocalTime d = LocalTime.of(12, 15, 33);
        String h = String.valueOf(d.getHour());
        String m = String.valueOf(d.getMinute());
        String s = String.valueOf(d.getSecond());
        System.out.print("\r"+h + ":" + m + ":" + s);

        //Update :
        Thread.sleep(1000);


     }

输出:

12:15:33 (time is not passing)

有人可以告诉我为什么它没有更新吗?以及如何从用户输入中获取与LocalTime对象一起运行的时间?

非常感谢您的时间!

java localtime
2个回答
1
投票

静态,非动态

有人可以告诉我为什么它没有更新吗?

A LocalTime代表一天中的特定时间。该对象是不变的,不变的,并且无法更新。

调用LocalTime.now()会捕获当天执行时间。该值稍后将not更改。要获取当天的当前时间稍后,请再次调用LocalTime.now()以获取新的新对象。

要显示LocalTime对象的值,请调用.toString以生成标准ISO 8701值的文本。对于其他格式,请使用DateTimeFormatter。搜索以了解更多信息,因为已经处理了很多次。

经过时间

而且如何从用户输入中获取与LocalTime对象一起运行的时间?

也许您是想确定从较早的时刻开始经过的时间,例如用户上一次执行特定动作或手势的时间。

所以我可以看到时间流逝

对于经过的时间,您需要跟踪时刻而不是时间。 Instant类表示UTC中的时刻。

Instant instant = Instant.now() ;  // Capture the current moment in UTC. 

Duration以小时-分钟-秒为单位计算经过时间。

Duration d = Duration.between( instant , Instant.now() ) ;

0
投票

如果您希望时钟在某个特定时间开始更新,请尝试类似的操作

LocalTime d = LocalTime.of(12, 15, 33);
LocalTime start = LocalTime.now();

for (int x = 0; x < 20; x++) {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    LocalTime now = LocalTime.now();
    Duration dur = Duration.between(start, now);
    start = now;
    d = d.plusSeconds(dur.getSeconds());
    System.out.println(d);
}
© www.soinside.com 2019 - 2024. All rights reserved.