问题
I want a clock that is set to an arbitrary time-of-day, then ticks in one-second increments.
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.
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();
}
}
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
duration = PT-10H-29M-4.832902S
localTime = 17:57:10
localTime = 17:57:11
localTime = 17:57:12
➥ I am I not properly using Clock.offset
? Or am I misunderstanding some concept here?
回答1:
The duration is the wrong way:
Duration duration = Duration.between( Instant.now(), odt.toInstant() ); // Flipped arguments
Output
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
回答2:
I think you can simply check if the number of second have changed, for example you can do this :
public static void main(String[] args) {
// hour of launch
String startTime = getTime();
// actual time;
String time = getTime();
// elapsed time in seconds.
int elapsedTime = 0;
while (true) {
if(!time.equals(getTime())) {
time = getTime();
// Output actual time.
System.out.println(time);
elapsedTime += 1;
}
}
}
public static String getTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
来源:https://stackoverflow.com/questions/58637015/using-java-time-clock-offset-to-increment-in-time-with-an-arbitrary-starting-tim