Date from() method in Java with Examples

The from(Instant inst) method of Java Date class returns an instance of date which is obtained from an Instant object.

Syntax:

public static Date from(Instant inst)

Parameters: The method takes one parameter inst of Instant type which is required to be converted.

Return Value: The method returns a date representing the same point on the timeline as the passing instant.

Exceptions:

  • NullPointerException: This is thrown when the instant is left null.
  • IllegalArgumentException: This is thrown when the instant is too large to be represented as a Date.

Below programs illustrate the use of from() Method in Java:
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate
// from() method of Date class
  
import java.time.Instant;
import java.util.Date;
  
public class JavaDateDemo {
    public static void main(String args[])
    {
        // Creating Date Object
        Date dateOne = new Date();
  
        // Creating Instant object
        Instant inst = Instant.now();
  
        // Displaying the instant
        System.out.println(
            "Present: "
            + dateOne.from(inst));
    }
}

chevron_right


Output:

Present: Tue Mar 26 06:45:40 UTC 2019

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.util.Date;
import java.util.Calendar;
import java.time.Instant;
  
public class GfG {
    public static void main(String args[])
    {
        // Creating a Calendar object
        Calendar c1 = Calendar.getInstance();
  
        // Set Month
        // MONTH starts with 0 i.e. ( 0 - Jan)
        c1.set(Calendar.MONTH, 00);
  
        // Set Date
        c1.set(Calendar.DATE, 30);
  
        // Set Year
        c1.set(Calendar.YEAR, 2019);
  
        // Creating a date object
        // with specified time.
        Date dateOne = c1.getTime();
  
        Instant inst = dateOne.toInstant();
  
        System.out.println(
            "Date: " + dateOne.from(inst));
    }
}

chevron_right


Output:

Date: Wed Jan 30 06:45:43 UTC 2019

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#from-java.time.Instant-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.