How to turn this unix epoch string "1583388944.0912497" into a Java Timestamp type?

Dan :

How can i turn this unix epoch "1583388944.0912497" into a Java Timestamp type?

Should i get rid of the precision numbers after the period in order to use Instant.from* or Long.valueOf?

Thanks

Basil Bourque :

Split the string into two parts, a count of whole seconds and a count of nanoseconds.

Avoid using floating point technology as it trades away accuracy for speed of execution.

String string = "1583388944.0912497" ;
String[] parts = string.split("\\.") ;
String part1 = parts[0] ; // 1583388944
String part2 = parts[1] ;  // 0912497

Parse as long integers. We must multiply the second part to get nanoseconds.

long seconds = Long.parseLong( part1 ) ;
long nanos = Long.parseLong( part2 ) * 100 ;

Feed to a factory method to instantiate an Instant object.

Instant instant = Instant.ofEpochSecond( seconds , nanos ) ;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=355472&siteId=1