I am receiving this value in a Json format:
{"time": 1643213994.7369497}
This time value is supposed to produce a DateTime value like this:
2021-08-12T03:03:31.656050 00:00
How can I get this value parsed into a LocalDateTime object or the format above?
CodePudding user response:
Assuming that number represents an Epoch Time, have you tried (in Java 8 ) rounding it up and using
LocalDateTime myLocalDateTime = Instant.ofEpochMilli(yourTimeHere).atZone(ZoneId.systemDefault()).toLocalDateTime();
for example?
You might want to replace ZoneId.systemDefault() with the ZoneID that is relevant to you.
CodePudding user response:
Since there's no timezone / offset information available in your source, you can convert it to an Instant and convert that to a ZonedDateTime or OffsetDateTime later.
A double like yours can be converted to an Instant using this method:
public static Instant toInstant(double value) {
final long epochSecond = (long) Math.floor(value);
final long nanoAdjustment = (long) ((value % 1.0) * 1000_000_000.0);
return Instant.ofEpochSecond(epochSecond, nanoAdjustment);
}
You can then later convert it to a ZonedDateTime like this:
Instant yourInstant = ...;
ZonedDateTime zdt = yourInstant.atZone(ZoneId.systemDefault());
