OffsetTime plusNanos() method in Java with Examples

The plusNanos() method of OffsetTime class used to add specified no of nanoseconds value to this OffsetTime and return the result as a OffsetTime object. This instant is immutable. The calculation wraps around midnight.

Syntax:

public OffsetTime plusNanos(long nanosecondsToAdd)

Parameters: This method accepts a single parameter nanosecondsToAdd which is the value of nanoseconds to be added, it can be a negative value.

Return value: This method returns a OffsetTime based on this time with the nanoseconds added.

Below programs illustrate the plusNanos() method:

Program 1:




// Java program to demonstrate
// OffsetTime.plusNanos() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a OffsetTime object
        OffsetTime time
            = OffsetTime.parse("12:25:10+01:00");
  
        // print OffsetTime
        System.out.println("OffsetTime before add: "
                           + time);
  
        // add 34000000 nanoseconds using plusNanos()
        OffsetTime value = time.plusNanos(34000000);
  
        // print result
        System.out.println("OffsetTime after add: "
                           + value);
    }
}


Output:

OffsetTime before add: 12:25:10+01:00
OffsetTime after add: 12:25:10.034+01:00

Program 2:




// Java program to demonstrate
// OffsetTime.plusNanos() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a OffsetTime object
        OffsetTime time
            = OffsetTime.parse("12:25:10+01:00");
  
        // print OffsetTime
        System.out.println("OffsetTime before add: "
                           + time);
  
        // add -971200000 nanoseconds  using plusNanos()
        OffsetTime value = time.plusNanos(-971200000);
  
        // print result
        System.out.println("OffsetTime after add: "
                           + value);
    }
}


Output:

OffsetTime before add: 12:25:10+01:00
OffsetTime after add: 12:25:09.028800+01:00

References: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetTime.html#plusNanos-long-



Contact Us