Java Duration Class | toNanos() Method with Example

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

Duration Class toNanos() method

  • toNanos() method is available in java.time package.
  • toNanos() method is used to convert this Duration into the number of nanoseconds.
  • toNanos() 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.
  • toNanos() method does not throw an exception at the time of converting this Duration to nanoseconds.

Syntax:

    public long toNanos();

Parameter(s):

  • None

Return value:

The return type of this method is long, it returns the number of nanoseconds exists in this Duration.

Example:

// Java program to demonstrate the example 
// of long toNanos() method of Duration

import java.time.*;

public class ToNanosOfDuration {
    public static void main(String args[]) {
        // Instantiates two Duration objects
        Duration du1 = Duration.ofSeconds(1);
        Duration du2 = Duration.parse("P0DT0H1M");

        // Display du1 and du2
        System.out.println("du1: " + du1);
        System.out.println("du2: " + du2);

        // represents this Duration du1 in seconds into
        // number of nanoseconds
        long to_nanos = du1.toNanos();

        // Display to_nanos
        System.out.println("du1.toNanos(): " + to_nanos);

        // represents this Duration du2 in minutes into
        // number of nanoseconds
        to_nanos = du2.toNanos();

        // Display to_nanos
        System.out.println("du2.toNanos(): " + to_nanos);
    }
}

Output

du1: PT1S
du2: PT1M
du1.toNanos(): 1000000000
du2.toNanos(): 60000000000






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.