Java Instant 舍入到下一秒

标签 java java-time

使用 Java Instant 类,如何舍入到最接近的秒数?不管是1毫秒、15毫秒还是999毫秒,都应该四舍五入到下一秒0毫秒。

我基本上想要,

Instant myInstant = ...

myInstant.truncatedTo(ChronoUnit.SECONDS);

但方向相反。

最佳答案

您可以使用 .getNano 来覆盖极端情况,以确保时间在秒上不完全均匀,然后使用 .plusSeconds() 添加额外的秒当有值要截断时。

    Instant myInstant = Instant.now();
    if (myInstant.getNano() > 0) //Checks for any nanoseconds for the current second (this will almost always be true)
    {
        myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1);
    }
    /* else //Rare case where nanoseconds are exactly 0
    {
        myInstant = myInstant;
    } */

我留在 else 语句中只是为了演示如果正好是 0 纳秒则不需要执行任何操作,因为没有理由不截断任何内容。

编辑:如果您想检查时间是否至少为 1 毫秒以进行四舍五入,而不是 1 纳秒,您可以将它与 1000000 纳秒进行比较,但保留 else 语句截断纳秒:

    Instant myInstant = Instant.now();
    if (myInstant.getNano() > 1000000) //Nano to milliseconds
    {
        myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1);
    }
    else
    {
        myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS); //Must truncate the nanoseconds off since we are comparing to milliseconds now.
    }

关于Java Instant 舍入到下一秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57274205/

相关文章:

java - 在 Applet 上使用 AWT 放大/缩小图表

java - 通过反射获取HashMap

java - ObjectMapper 截断 Map 中的日期

java - Libgdx - Mtx 纹理未显示在屏幕上

java - Dr Java 代码错误

java - spring中创建ThreadPoolExecutor会导致内存泄漏吗?

java - 将 java.util.Date 转换为 java.time.LocalDate

java - Java 日期解析代码有什么问题?

java - 如何根据 1 小时间隔获取时间段

java - Java 8 time api 如何选择 DST 更改周期的偏移量