.from()
Anonymous contributor
Published Aug 11, 2023
Contribute to Docs
The ‘Date.from()’ method returns an Instant
object of a given Date
. An Instant
provides more accuracy than a Date
because it reports nanoseconds (while Dates
are limited to milliseconds).
Syntax
someDate.from(inst)
The Date.from()
method is used in combination with an Instant
object inst
.
In Java from
is not a keyword. The from
method can be used with the Date class to retrieve the current day, date, time, timezone and year.
Date today = new Date();Instant inst = Instant.now();System.out.println(today.from(inst));
Example
The following example uses the words "apples"
and "oranges"
to avoid syntax confusion:
import java.time.Instant;import java.util.Date;class JavaDateDemo {public static void main(String args[]){// This line creates a Date object called "apples".Date apples = new Date();// This line creates an Instant object called "oranges".Instant oranges = Instant.now();// This line displays the instant using the .from() method.System.out.println("Present day, date, time, timezone and year: "+ apples.from(oranges));}}
The output will be the exact day, date, time, timezone and year of the moment the query is submitted:
Present day, date, time, timezone and year: Wed Aug 02 11:06:16 AKDT 2023
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours