0

I am struggling to get the unix time epoch with microseconds in this format(1586420933.453254). I tried different classes.

- java.utils.Calendar
- java.time.Instant
- org.joda.time.DateTime

But I am getting only milliseconds like this - 1586420933453

How do I get the unix epoch with microseconds like this 1586420933.453254 in Java.

1
  • 1
    See the documentation for Instant and the relevant methods on System. If Instant isn't providing that resolution, the system clock may not have it. Specify your runtime platform. Commented Apr 9, 2020 at 8:52

1 Answer 1

3

You can easily do it using standard java time Instant + a number format. Keep in mind the result will be in UTC, though. Here is a draft with current time:

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.Instant;


Instant datetime = Instant.now();

// Extract needed information: date time as seconds + fraction of that second
long secondsFromEpoch = datetime.getEpochSecond();
int nanoFromBeginningOfSecond = datetime.getNano();
double nanoAsFraction = datetime.getNano()/1e9;

// Now, let's put that as text
double epochSecondUTCPlusNano = secondsFromEpoch + nanoAsFraction;
NumberFormat format = DecimalFormat.getInstance();
format.setMinimumFractionDigits(6);
format.setMaximumFractionDigits(6);
format.setGroupingUsed(false);
System.out.print(format.format(epochSecondUTCPlusNano));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. I got this "1586426623.416" value. But it is not getting microsecond value.
Sorry, but I don't understand. .416 is the fraction of second, therefore the microsecond value. If you need exactly 6 fraction digits, you can add a line of configuration for the number format: format.setMinimumFractionDigits(6).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.