Javaexercise.com

Get LocalDateTime With Altered Nanoseconds Of Time In Java

If you want to get the same date and time but the altered nanoseconds then use the withNano() method and add the nanos as much as you want but within the range(0 to 999,999,999).

In this article, we are going to add/alter nanoseconds to the existing localdatetime by using the built-in method.

Let's see the code example.

Alter Nanoseconds of LocalDateTime in Java

Here, we first get the current date and time using the Localdatetime class and then we used the withNano() method to alter the nanoseconds of this date-time.

You can notice that the date-time is the same(not altered) except for the nano field. 

/* 
 *  Code example to get localdatetime with the specified nanoseconds in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// Current date and time
		LocalDateTime date = LocalDateTime.now();

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get new datetime with altered nanoseconds
		LocalDateTime newDate = date.withNano(45);

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T12:45:20.222034257
New date : 2022-03-17T12:45:20.000000045

 

Now,  let's have a look at this method signature:

public LocalDateTime withNano(int nanoOfSecond)

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns a copy of localdatetime after altering the specified number of nanoseconds, not null.

Parameters: It takes a single int type value. It can be 0 to 999,999,999

Exceptions: It throws a DateTimeException if the nano value is invalid.

 

If the value of nanoseconds is passed outside the range then this method returns an exception. Here, we passed a value outside the range.

package javaexample;
/* 
 *  Code example to get localdatetime with the specified nanoseconds in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// Current date and time
		LocalDateTime date = LocalDateTime.now();

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get new datetime with altered nanoseconds
		LocalDateTime newDate = date.withNano(1099999999); // invalid range

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T12:54:30.633592320
Exception in thread "main" java.time.DateTimeException: Invalid value for NanoOfSecond (valid values 0 - 999999999): 1099999999