Syntax error Instant truncatedTo() method in Java

Instant truncatedTo() method in Java



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);
Updated on: 2019-07-30T22:30:25+05:30

946 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements