Javaexercise.com

How To Get nanoseconds From LocalDateTime In Java?

To get nanoseconds from a local date-time, Java provides a class i.e. LocalDateTime, and a built-in method i.e. getNano().

Here, we are getting nanoseconds from the local date-time in Java.

Let's see the code below. 

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

		// String  date is given
		String strDate = "2022-03-14T17:28:13.048999208";
		// parse the string date into date time
		LocalDateTime date = LocalDateTime.parse(strDate);

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

		// Get nenoseconds from the date
		int nanoSeconds = date.getNano();

		// Display result
		System.out.println("Nano Seconds : "+nanoSeconds);
	}
}

Output:

Date : 2022-03-14T17:28:13.048999208
Nano Seconds : 48999208
 

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

public int getNano()

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns the nano-of-seconds, from 0 to 999,999,999.

Parameters: No parameter.

Exceptions: No exceptions.

Version: Since 1.8

How to get nanoseconds from the current local date-time in Java

If you wish to get the nanoseconds from the current local date-time, see the below code.

Here, first, we used the now() method to get the current date-time and then the getNano() to get Nanos.

/* 
 *  Code example to get nenoseconds from localdatetime 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 nenoseconds from the date
		int nanoSeconds = date.getNano();

		// Display result
		System.out.println("Nano Seconds : "+nanoSeconds);
	}
}

Output:

Date : 2022-03-16T12:24:34.969457473
Nano Seconds : 969457473