简体   繁体   English

带有小数秒的Java时间戳

[英]Java Timestamp with Fractional Seconds

How can I print Java Instant as a timestamp with fractional seconds like 1558766955.037 ? 如何将Java Instant作为带有1558766955.037的小数秒的时间戳打印? The precision needed is to 1/1000, as the example shows. 如示例所示,所需的精度为1/1000。

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 . 我尝试了(double) timestamp.getEpochSecond() + (double) timestamp.getNano() / 1000_000_000 ,但是当我将其转换为字符串并打印时,它显示1.558766955037E9

The result you're seeing is the secientific (e-) notation of the result you wanted to get. 您看到的结果是您想要得到的结果的科学(e-)表示法 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);

As others pointed out it is formatting issue. 正如其他人指出的那样,这是格式化问题。 For your specific format you could use Formatter with Locale that supports dot delimetted fractions : 对于您的特定格式,您可以将FormatterLocale一起使用,以支持点除法的分数:

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

System.out.printf("%.3f", instant.toEpochMilli() / 1000.0)应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM