Date.from(Instant): This method is available in java.util.Date class of Java.
Syntax:
Date java.util.Date.from(Instant instant)
This method takes one argument of type Instant as its parameter. This method obtains an instance of Date from an Instant object.
Note: Instant uses a precision of nanoseconds, whereas Dateuses a precision of milliseconds.
Parameters: One parameter is required for this method.
instant: the instant to convert.
Returns: a Date representing the same point on the timeline as the provided instant.
Throws:
1. NullPointerException - if instant is null.
2. IllegalArgumentException - if the instant is too large to represent as a Date.
Approach 1: When no exception
Java
import java.time.Instant;import java.util.Date;public class Datefrom {public static void main(String[] args) {Date date = new Date();Instant instant = date.toInstant();System.out.println(Date.from(instant));}}
Output:
Sun Jan 30 18:01:46 IST 2022
Approach 2: NullPointerException
Java
import java.time.Instant;import java.util.Date;public class Datefrom {public static void main(String[] args) {Instant instant = null;System.out.println(Date.from(instant));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.time.Instant.toEpochMilli()" because "instant" is null at java.base/java.util.Date.from(Date.java:1363)
No comments:
Post a Comment