1

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

Dan
  • 2,209
  • 3
  • 23
  • 44
  • I recommend you don’t use `Timestamp`. That class is poorly designed and long outdated. Instead use `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) (or `LocalDateTime` if for a timestamp without time zone in SQL, not recommended). – Ole V.V. Mar 29 '20 at 06:26

1 Answers1

1

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 ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Thanks, that worked for me after using a regex in .split and using Long.valueOf instead of Long.parse – Dan Mar 29 '20 at 05:25
  • 2
    @Dan I will assume you are right about escaping the FULL STOP for regex syntax. (I’ve not run the code yet.) But choose `parseLong` over `valueOf` to avoid unnecessary auto-boxing. The `Instant.ofEpochSecond` method takes primitive `long` rather than `Long` objects. – Basil Bourque Mar 29 '20 at 05:45
  • That should work for the cases like the one on the question. What I don’t like about it is (1) if there are 6 or 8 fractional decimals instead, it will tacitly produce an inaccurate result. It would be better either to throw an exception or take a varaible number of decimals into account. (2) The same for a negative number for a timestamp before 1970. – Ole V.V. Mar 29 '20 at 06:23