J Freebird
J Freebird

Reputation: 3910

Java Timestamp with Fractional Seconds

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.

Upvotes: 1

Views: 2234

Answers (3)

Michał Krzywański
Michał Krzywański

Reputation: 16910

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

Upvotes: 1

Mureinik
Mureinik

Reputation: 311528

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);

Upvotes: 1

Slawomir Chodnicki
Slawomir Chodnicki

Reputation: 1545

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

Upvotes: 0

Related Questions