What is Duration.withSeconds() in Java?

Overview

withSeconds() is an instance method of the Duration class. It is used to return a copy of a Duration object with the number of seconds set to the passed value. The nanosecond part of the Duration object is retained without any change.

The withSeconds() method is 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;

Syntax

public Duration withSeconds(long seconds)

Parameters

  • long seconds: The seconds to represent. This value can be positive or negative.

Return value

This method returns a new Duration object.

Code

import java.time.Duration;
public class Main {
public static void main(String[] args) {
Duration duration = Duration.ofSeconds(143234, 4223);
int noOfSecondstoSet = 456;
Duration newDuration = duration.withSeconds(noOfSecondstoSet);
System.out.printf("Original Duration Object - %s\nCloned Duration Object with different seconds value - %s", duration, newDuration);
}
}

Explanation

  • Line 1: We import the Duration class.
  • Line 6: We define a Duration object using the ofSeconds() method.
  • Line 8: We define the number of seconds value to set in the new Duration object.
  • Line 10: We clone the object created in line 6 using the withSeconds() method by passing the new number of seconds value defined in line 8.
  • Line 10: We print the original Duration object and the cloned Duration object.

Free Resources