ofInstant(Instant instant, ZoneId zone) method of LocalDateTime class in Java is used to create an instance of LocalDateTime using an Instant and zone ID. These two parameters are passed to the method and method returns LocalDateTime on the basis of these two parameters. The calculation of the LocalDateTime follows the following step.
Java
Java
- The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.
- Finally, the local date-time is calculated using the instant and the obtained offset.
public static LocalDateTime
ofInstant(Instant instant,
ZoneId zone)
Parameters: The method accepts two parameters:
- instant - It is of Instant type and represents the instant passed to create localdatetime.
- zone - It is of ZoneId type and represents the time-zone used for creating the offset.
// Java program to demonstrate
// LocalDateTime.ofInstant(
// Instant instant, ZoneId zone) method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// Create LocalDateTime object
LocalDateTime localdatetime
= LocalDateTime.ofInstant(
Instant.now(),
ZoneId.systemDefault());
// Print full date
System.out.println(
"Date: " + localdatetime);
}
}
Output:
Program 2:
Date: 2020-05-13T12:40:38.087
// Java program to demonstrate
// LocalDateTime.ofInstant(
// Instant instant, ZoneId zone) method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// Create LocalDateTime object
LocalDateTime localdatetime
= LocalDateTime.ofInstant(
Instant.now(),
ZoneId.systemDefault());
// Print year only
System.out.println(
"Year: " + localdatetime.getYear());
}
}
Output:
References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#ofInstant(java.time.Instant, java.time.ZoneId)Year: 2020