1

How can I print Java Instant as a timestamp with fractional seconds like 1558766955.037 ? The precision needed is to 1/1000, as the example shows.

I tried (double) timestamp.getEpochSecond() + (double) timestamp.getNano() / 1000_000_000, but when I convert it to string and print it, it shows 1.558766955037E9.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
J Freebird
  • 3,664
  • 7
  • 46
  • 81
  • 1
    It sounds like this is a *display* issue as much as anything else - if you write `double value = 1558766955.037;` and print that, I suspect you'll get the same result. So at that point, the problem isn't around timestamps - it's number formatting. I expect you'll find some other Stack Overflow questions around that. – Jon Skeet May 25 '19 at 07:01
  • @JonSkeet That's actually correct. Thank you. – J Freebird May 25 '19 at 07:08

3 Answers3

1

The result you're seeing is the secientific (e-) notation of the result you wanted to get. In other words, you have the right result, you just need to properly format it when you print it:

Instant timestamp = Instant.now();
double d = (double) timestamp.getEpochSecond() + (double) timestamp.getNano() / 1000_000_000;
System.out.printf("%.2f", d);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

As others pointed out it is formatting issue. For your specific format you could use Formatter with Locale that supports dot delimetted fractions :

Instant now = Instant.now();

double val = (double) now.getEpochSecond() + (double) now.getNano() / 1000_000_000;

String value = new Formatter(Locale.US)
                .format("%.3f", val)
                .toString();

System.out.print(value);

Prints :

1558768149.514
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
0

System.out.printf("%.3f", instant.toEpochMilli() / 1000.0) should work.

Slawomir Chodnicki
  • 1,525
  • 11
  • 16