-1

I can convert 19 digit unix timestamp to LocalDateTime like this

Instant instant =
                    Instant.ofEpochSecond(
                            TimeUnit.NANOSECONDS.toSeconds(timestamp),
                            (timestamp % 1_000_000_000L));
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

How do i do that for 16 digit ( microseconds ) timestamp ? How to convert back to 19 / 16 digit timestamp from LocalDateTime ?

Thanks

willy
  • 225
  • 1
  • 4
  • 16
  • Did you have a look at the documentation yet? There is a `LocalDateTime.toInstant(ZoneOffset)` which you could use to convert back to `Instant` and then call `toEpochMilli()` and `getNanon()` on that instant. – Thomas Jun 15 '21 at 09:56
  • Its like asking "I can round down 5.2 to 5.0, but how can I convert 5.0 to 5.2" You cannot add precision if you have not stored the discarded value in some variable and come up with some solution to add that precision to the converted value. – bradley101 Jun 15 '21 at 09:59
  • Prefer `ZonedDatteTime` for a date and time in your own (local) time zone. Also by converting to `LocalDateTime` you are throwing away information, which will make the opposite conversion impossible. – Ole V.V. Jun 15 '21 at 19:01

1 Answers1

1

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.

dan1st
  • 12,568
  • 8
  • 34
  • 67