LocalDateTime withNano() method in Java with Examples
Last Updated :
29 Oct, 2021
withNano() method of LocalDateTime class in Java is used to get a copy of this LocalDateTime with the nano-seconds changed to the nano-seconds passed as the parameter to this method. The remaining values of this LocalDateTime remain the same.
Syntax:
public LocalDateTime withNano(int nanoSeconds)
Parameter: Single mandatory parameter nanoSeconds which specify the nano-seconds to be set in the resultant LocalDateTime instance. The value of these nano-seconds can range from 0 to 999999999.
Return Type: A LocalDateTime instance with the nano-seconds changed to the nano-seconds passed as the parameter to this method. The remaining values of this LocalDateTime remain the same.
Exceptions: The function throws a DateTimeException if the nano-seconds value is invalid.
Example 1:
Java
import java.time.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
LocalDateTime dt = LocalDateTime.now();
System.out.println( "Original LocalDateTime: "
+ dt.toString());
System.out.println( "New LocalDateTime: "
+ dt.withNano( 0 ));
}
}
|
Output:
Original LocalDateTime: 2018-11-30T12:54:17.484
New LocalDateTime: 2018-11-30T12:54:17
Example 2:
Java
import java.time.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
LocalDateTime dt
= LocalDateTime.parse( "2015-04-06T10:15:30" );
System.out.println( "Original LocalDateTime: "
+ dt.toString());
System.out.println( "New LocalDateTime: "
+ dt.withNano( 99999 ));
}
}
|
Output:
Original LocalDateTime: 2015-04-06T10:15:30
New LocalDateTime: 2015-04-06T10:15:30.000099999
Now we will be handling with care withNano(0) method is used for removing the nano seconds and retaining date-time till seconds.
Example 3:
Note: Special Case: If the seconds value is:00, then while doing at toString() will eliminate the seconds portion.
Example:
Java
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class GFG {
public static void main(String[] args)
throws InterruptedException
{
DateTimeFormatter dtf
= DateTimeFormatter.ISO_DATE_TIME;
while ( true ) {
Thread.sleep( 500 );
System.out.println( "Original :00 seconds --> "
+ LocalDateTime.now());
System.out.println(
"Without Formatter(Observe when seconds is :00) --> "
+ LocalDateTime.now().withNano( 0 ));
System.out.println(
"With Formatter -> "
+ LocalDateTime.now().withNano( 0 ).format(
dtf));
}
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...