使用java.time.Clock.offset以任意的起始时间在时间​​上递增 [英] Using java.time.Clock.offset to increment in time with an arbitrary starting time-of-day

查看:104
本文介绍了使用java.time.Clock.offset以任意的起始时间在时间​​上递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将时钟设置为任意一天的时间,然后以一秒为增量计时。

I want a clock that is set to an arbitrary time-of-day, then ticks in one-second increments.

例如,以 14:55:20开头;。然后我的应用应输出 14:55:20, 14:55:21, 14:55:22。等等,以一秒钟为间隔。

For example, start with "14:55:20". Then my app should output "14:55:20", "14:55:21", "14:55:22" and so on in one-second ticks.

似乎 Clock.offset 就是要这样做。要引用该文档,请执行以下操作:

It would seem that Clock.offset is meant to do just this. To quote the doc:


获得一个时钟,该时钟从指定的时钟返回具有指定持续时间的时刻

Obtains a clock that returns instants from the specified clock with the specified duration added

所以我尝试了以下操作:

So I tried the following:

LocalTime localTime = LocalTime.parse( "14:55:20" );
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ).with( localTime );
Duration duration = Duration.between( odt.toInstant() , Instant.now() );
Clock clock = Clock.offset( Clock.systemUTC() , duration );

System.out.println( "odt = " + odt );
System.out.println( "duration = " + duration );

for ( int i = 1 ; i < 10 ; i++ )
{
    LocalTime lt = OffsetDateTime.now( clock ).truncatedTo( ChronoUnit.SECONDS ).toLocalTime();
    System.out.println( "localTime = " + lt );
    try
    {
        Thread.sleep( TimeUnit.SECONDS.toMillis( 1 ) );
    }
    catch ( InterruptedException e )
    {
        e.printStackTrace();
    }
}

我最初的起点是 odt 似乎正确。但是随后我对 OffsetDateTime.now(clock)的调用未产生预期的结果。

My initial starting point with odt seems right. But then my calls to OffsetDateTime.now( clock ) are not producing the desired outcome.


odt = 2019-10-31T14:55:20Z

odt = 2019-10-31T14:55:20Z

持续时间= PT-10H-29M-4.832902S

duration = PT-10H-29M-4.832902S

localTime = 17:57:10

localTime = 17:57:10

localTime = 17:57:11

localTime = 17:57:11

localTime = 17:57:12

localTime = 17:57:12

➥我不能正确使用 Clock.offset 吗?还是我在这里误解了一些概念?

➥ I am I not properly using Clock.offset? Or am I misunderstanding some concept here?

推荐答案

持续时间是错误的方式:

The duration is the wrong way:

Duration duration = Duration.between( Instant.now(), odt.toInstant() ); // Flipped arguments

输出

odt = 2019-10-31T14:55:20Z
duration = PT8H1M41.0216146S
localTime = 14:55:20
localTime = 14:55:21
localTime = 14:55:22
localTime = 14:55:23
localTime = 14:55:24
localTime = 14:55:25
localTime = 14:55:26
localTime = 14:55:27
localTime = 14:55:28

这篇关于使用java.time.Clock.offset以任意的起始时间在时间​​上递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆