Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What are toNanosPart() and toDaysPart() in Java duration class?

abhilash

The toDaysPart() method

toDaysPart() is an instance method of the Duration that obtains the number of days in the Duration object. The number of days is calculated by dividing the number of seconds of the Duration object by 86400. This is based on the traditional 24-hour definition of a day. This method was introduced in Java version 9.

Syntax

public long toDaysPart()

Parameters

The method has no parameters.

Return value

This method returns the number of days in the Duration object:

The toNanosPart() method

toNanosPart() is an instance method of the Duration which is used to obtain the number of nanoseconds part in the Duration object. The number of nanoseconds part is the number of nanoseconds stored in the Duration object. This method was introduced in Java version 9.

Syntax

public int toNanosPart()

Parameters

The method has no parameters.

Return value

This method returns the number of nanoseconds part in the Duration object.

The toDaysPart and toNanosPart methods are defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class check the following import statement:

import java.time.Duration;

Code

import java.time.Duration;

public class Main {

    public static void daysPart(){
        Duration duration = Duration.ofSeconds(143234);

        long numOfDays = duration.toDaysPart();

        System.out.printf("Number of days in %s is %s", duration, numOfDays);
        System.out.println();
    }

    public static void nanosPart(){
        Duration duration = Duration.ofSeconds(143234, 4223);

        long numOfNanoSecondsPart = duration.toNanosPart();

        System.out.printf("The number of nanoseconds part in %s is %s", duration, numOfNanoSecondsPart);
        System.out.println();
    }

    public static void main(String[] args) {
        daysPart();
        nanosPart();
    }
}
"toDaysPart" and "toNanosPart" method

Explanation

  • Line 1: We import the Duration class.
  • Lines 5-12: We define a method called daysPart() that creates a Duration object using the ofSeconds() method and prints the number of days using the toDaysPart() method.
  • Lines 14-21: We define a method called nanosPart() that creates a Duration object using the ofSeconds() method. It also prints the number of nanoseconds part using the toNanosPart() method.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring