即时 truncatedTo() 方法在 Java 中


可以在 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

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

首先显示当前 Instant。然后使用 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);

更新日期:2019 年 7 月 30 日

743 次浏览

开启你的 职业

完成课程并获得认证

开始学习
广告
© . All rights reserved.