Java 中的 Instant truncatedTo() 方法

java 8object oriented programmingprogramming

可以使用 Java 中 Instant 类的 truncatedTo() 方法获取不可变的截断 Instant。该方法需要一个参数,即 Instant 截断到的 TemporalUnit,并返回不可变的截断 Instant。

以下程序演示了此过程 −

示例

import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant instant = Instant.now();
      System.out.println("The current instant is: " + instant);
      Instant truncatedInstant = instant.truncatedTo(ChronoUnit.MINUTES);
      System.out.println("The truncated instant is: " + truncatedInstant);
   }
}

输出

The current instant is: 2019-02-13T08:49:09.188Z
The truncated instant is: 2019-02-13T08:49:00Z

现在让我们理解一下上面的程序。

首先显示当前时刻。然后使用 truncatedTo() 方法获取不可变的截断 Instant 并显示它。演示此操作的代码片段如下 −

Instant instant = Instant.now();
System.out.println("The current instant is: " + instant);
Instant truncatedInstant = instant.truncatedTo(ChronoUnit.MINUTES);
System.out.println("The truncated instant is: " + truncatedInstant);

相关文章