英文:
Java - get unix epoch with microsecond
问题
我在尝试以这种格式(1586420933.453254)获取带微秒的Unix时间戳。我尝试了不同的类。
- java.utils.Calendar
- java.time.Instant
- org.joda.time.DateTime
但我只能得到毫秒,像这样 - 1586420933453
我该如何在Java中获得带微秒的Unix时间戳,就像这样的格式 1586420933.453254。
英文:
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
得分: 3
你可以使用标准的Java时间Instant和数字格式很容易地完成这个操作。请注意,结果将以UTC时间显示。以下是一个带有当前时间的草稿:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.Instant;
Instant datetime = Instant.now();
// 提取所需信息:将日期时间转换为秒数 + 秒数内的纳秒部分
long secondsFromEpoch = datetime.getEpochSecond();
int nanoFromBeginningOfSecond = datetime.getNano();
double nanoAsFraction = datetime.getNano()/1e9;
// 现在,让我们将它转换为文本
double epochSecondUTCPlusNano = secondsFromEpoch + nanoAsFraction;
NumberFormat format = DecimalFormat.getInstance();
format.setMinimumFractionDigits(6);
format.setMaximumFractionDigits(6);
format.setGroupingUsed(false);
System.out.print(format.format(epochSecondUTCPlusNano));
英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论