Java – 获取带有微秒的Unix时间戳

huangapple go评论76阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年4月9日 16:37:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/61117125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定