Java LocalDateTime Class | from() Method with Example

LocalDateTime Class from() method: Here, we are going to learn about the from() method of LocalDateTime Class with its syntax and example.
Submitted by Preeti Jain, on June 04, 2020

LocalDateTime Class from() method

  • from() method is available in java.time package.
  • from() method is used to get a copy of date-time from the given TemporalAccessor object.
  • from() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • from() method may throw an exception at the time of returning LocalDateTime from the given temp_acc.
    DateTimeException – This exception may throw when the given temp_acc couldn’t convert into LocalDateTime.

Syntax:

    public static LocalDate from(TemporalAccessor temp_acc);

Parameter(s):

  • TemporalAccessor temp_acc – represents the temporal accessor to convert to LocalDateTime.

Return value:

The return type of this method is LocalDateTime, it returns the LocalDateTime that holds the value converted from the given object into date-time.

Example:

// Java program to demonstrate the example 
// of from(TemporalAccessor temp_acc)
// method of LocalDateTime

import java.time.*;

public class FromOfLocalDateTime {
    public static void main(String args[]) {
        // Instantiates an OffsetDateTime 
        // and a ZonedDateTime object
        OffsetDateTime off_da_time = OffsetDateTime.now();
        ZonedDateTime zo_da_time = ZonedDateTime.parse("2008-07-06T20:25:30.213+03:00[Africa/Asmara]");

        // Display off_da_time, zo_da_time
        System.out.println("OffsetDateTime off_da_time: ");
        System.out.println("off_da_time: " + off_da_time);
        System.out.println();
        System.out.println("ZonedDateTime zo_da_time: ");
        System.out.println("zo_da_time: " + zo_da_time);

        System.out.println();

        // Here, this method creates a date-time 
        // object from a temporal object i.e. here
        // we are creating date-time from OffsetDateTime
        LocalDateTime da_ti = LocalDateTime.from(off_da_time);

        // Display da_ti
        System.out.println("LocalDateTime.from(off_da_time): " + da_ti);

        // Here, this method creates a date-time 
        // object from a temporal object i.e. here
        // we are creating date-time from ZonedDateTime
        da_ti = LocalDateTime.from(zo_da_time);

        // Display da_ti
        System.out.println("LocalDateTime.from(zo_da_time): " + da_ti);
    }
}

Output

OffsetDateTime off_da_time: 
off_da_time: 2020-06-04T08:53:13.465511Z

ZonedDateTime zo_da_time: 
zo_da_time: 2008-07-06T20:25:30.213+03:00[Africa/Asmara]

LocalDateTime.from(off_da_time): 2020-06-04T08:53:13.465511
LocalDateTime.from(zo_da_time): 2008-07-06T20:25:30.213


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.