Creating specific date object from milli seconds in different time

I'm working with an API that has a different time than the program's machine. I can retrieve the time of the server, which will returns milliseconds.

e.g

long serverTime = api.getTime()

Since I know the server time, can I somehow create a date object from this millisecond that would represent certain dates, but with server time?

For example, API is only available from 8:00 to 16:00 UTC ( machine time is +1 hour ). My use case requires me to send data using this API as soon as possible ( the sooner I send data, the sooner they get processed, and the sooner other tasks can start running and so on, unfortunately, every millisecond spared is good ). So far I am doing something like this

// create date time when i want to do something with API in my time
 LocalDateTime time = LocalDateTime.of(2021, 3, 26, 9, 0, 0);
 long targetMillis = time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

 long serverTime = api.getTime()
 // calculate diff
 long serverTimeDiff = client.getServerTime() - System.currentTimeMillis();

// sleep thread till the time is right. Sleep 1 minute less to start busy waiting to get some extra 
// spared millis
 Thread.sleep((targetMillis - serverTime) - minutesToMilliseconds(1) );
 while( System.currentTimeMillis() + serverTimeDiff < ( targetMillis - 50 ) ){
        //busy waiting
 }
  
 api.sendData(..);

however, the time diff may not be that accurate ( change in few millis ), is there some way how to create something like:

long serverTime = api.getTime()
Instant date = Instant.ofEpochMilli(serverTime).setHour(..).setMinute(..).setSecond(..);

so I can calculate the diff more accurately with something like

Thread.sleep((targetMillis - date.toMillis().toEpochMilli) - minutesToMilliseconds(1))

and thus possibly save some milliseconds?

Thanks for the help!



from Recent Questions - Stack Overflow https://ift.tt/3fsqskr
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)