Java Instant Class | truncatedTo() Method with Example

Instant Class truncatedTo() method: Here, we are going to learn about the truncatedTo() method of Instant Class with its syntax and example.
Submitted by Preeti Jain, on May 28, 2020

Instant Class truncatedTo() method

  • truncatedTo() method is available in java.time package.
  • truncatedTo() method is used to get an Instant that holds the value of this Instant truncated to the given unit.
  • truncatedTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • truncatedTo() method may throw an exception at the time of truncating.
    • DateTimeException: This exception may throw when the given unit can't truncate due to an invalid unit.
    • UnsupportedTemporlTypeException: This exception may throw when the given unit is unsupported.

Syntax:

    public Instant truncatedTo(TemporalUnit t_unit);

Parameter(s):

  • TemporalUnit t_unit – represents the unit to truncate from this Instant.

Return value:

The return type of this method is Instant, it returns the Instant that holds the value truncated the given unit from this Instant.

Example:

// Java program to demonstrate the example 
// of truncatedTo(TemporalUnit t_unit) method 
// of Instant

import java.time.*;
import java.time.temporal.*;

public class TruncatedToOfInstant {
    public static void main(String args[]) {
        // Instantiates two Instant
        Instant ins1 = Instant.parse("2006-04-03T05:10:15.60Z");
        Instant ins2 = Instant.now();

        // Display ins1,ins2 
        System.out.println("Instant ins1 and ins2: ");
        System.out.println("ins1: " + ins1);
        System.out.println("ins2: " + ins2);

        System.out.println();

        // Here, this method truncates the given 
        // unit from this Instant i.e. here
        // we are truncating SECONDS unit
        // from this Instant ins1
        Instant ins = ins1.truncatedTo(ChronoUnit.SECONDS);

        // Display ins
        System.out.println("ins1.truncatedTo(ChronoUnit.SECONDS): " + ins);

        // Here, this method truncates the given 
        // unit from this Instant i.e. here
        // we are truncating MINUTES unit
        // from this Instant ins2
        ins = ins2.truncatedTo(ChronoUnit.MINUTES);

        // Display ins
        System.out.println("ins2.truncatedTo(ChronoUnit.MINUTES): " + ins);
    }
}

Output

Instant ins1 and ins2: 
ins1: 2006-04-03T05:10:15.600Z
ins2: 2020-05-27T06:11:43.033792Z

ins1.truncatedTo(ChronoUnit.SECONDS): 2006-04-03T05:10:15Z
ins2.truncatedTo(ChronoUnit.MINUTES): 2020-05-27T06:11:00Z


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.