Instant truncatedTo() method in Java

Java 8Object Oriented ProgrammingProgramming

An immutable truncated Instant can be obtained using the truncatedTo() method in the Instant class in Java. This method requires a single parameter i.e. the TemporalUnit till which the Instant is truncated and it returns the immutable truncated Instant.

A program that demonstrates this is given as follows −

Example

 Live Demo

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

Output

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

Now let us understand the above program.

First the current instant is displayed. Then the immutable truncated Instant is obtained using the truncatedTo() method and it is displayed. A code snippet that demonstrates this is as follows −

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);
raja
Published on 26-Mar-2019 05:18:40

Advertisements