You can use Instant.ofEpochMilli
in order to get the time from the timestamp with milliseconds and then add the microseconds with Instant#plusNanos
.
It would look like this:
Instant instant = Instant.ofEpochMillis(timestamp/1_000).plusNanos(timestamp%1_000);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
timestamp/1_000
gets the time in milliseconds truncating the microseconds and plusNanos(timestamp%1_000)
adds the microseconds part and returns a new Instant
with that.
This Instant
with the correct microseconds time can then be used in order to get the LocalDateTime
.
For copying back, you can convert it to s ZonedDateTime
and to an Instant
afterwards like described here:
ZonedDateTime zonedTimestamp=yourLocalDateTime.atZone(ZoneId.systemDefault());
Instant convertedInstant=zonedTimestamp.toInstant();
long recreatedTimeMicros=convertedInstant.toEpochMillis()*1_000+(convertedInstant.getNano()/1_000)%1_000;
This converts the LocalDateTime
to a ZonedDateTime
with your default timezone (that you used in the other direction) and gets the epoch milliseconds and adds the nanosecond to it.
Note that getNanos()
gets the nanoseconds since the last second. The milliseconds need to be multiplied with 1000 so that it is in microseconds and the nanoseconds are divided by 1000 for the same reason. Furthermore, the modulo operation is required so that you don't count the milliseconds multiple times.