Java Instant Class | now() Method with Example

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

Instant Class now() method

Syntax:

    public static Instant now();
    public static Instant now(Clock cl);
  • now() method is available in java.time package.
  • now() method is used to get the current instant generated from the system clock.
  • now(Clock cl) method is used to return the current instant generated from the given Clock.
  • These methods don't throw an exception at the time of calculating the remainder.
  • These are static methods and it is accessible with the class name and if we try to access these methods with the class object then we will not get an error.

Parameter(s):

  • In the first case, "now()",
    • None
  • In the second case, "now(Clock cl)",
    • Clock cl – represents the clock to use to represent this Instant.

Return value:

In both the cases, the return type of the method is Instant,

  • In the first cases, it returns the Instant obtained from the system clock.
  • In the second cases, it returns the Instant obtained from the given clock.

Example:

// Java program to demonstrate the example 
// of now() method of Instant

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

public class NowOfInstant {
    public static void main(String args[]) {
        // Instantiates a ZoneId for Accra
        // and a Clock object
        ZoneId zone = ZoneId.of("Africa/Accra");
        Clock cl = Clock.system(zone);

        // Here, this method returns the
        // current instant from the default 
        // system clock
        Instant ins = Instant.now();

        // Display ins
        System.out.println("Instant.now(): " + ins);


        // Here, this method returns the
        // current instant from the given 
        // clock (cl)
        ins = Instant.now(cl);

        // Display ins
        System.out.println("Instant.now(cl): " + ins);
    }
}

Output

Instant.now(): 2020-05-28T01:17:43.547677Z
Instant.now(cl): 2020-05-28T01:17:43.618370Z


Comments and Discussions!

Load comments ↻





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