Close

Java Date Time - LocalDateTime.from() Examples

Java Date Time Java Java API 


Class:

java.time.LocalDateTime

java.lang.Objectjava.lang.Objectjava.time.LocalDateTimejava.time.LocalDateTimejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.time.chrono.ChronoLocalDateTimeChronoLocalDateTimejava.io.SerializableSerializableLogicBig

Method:

public static LocalDateTime from(TemporalAccessor temporal)

The static method LocalDate.from(TemporalAccessor temporal) returns the LocalDateTime instance based on the provided TemporalAccessor.

The provided temporal accessor must have all fields needed for the LocalDateTime instance to be created otherwise DateTimeException will be thrown.



Examples


package com.logicbig.example.localdatetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class FromExample {

public static void main (String... args) {
ZonedDateTime z = ZonedDateTime.of(2016, 10, 12,
15, 20, 30, 0,
ZoneId.systemDefault());
System.out.println(z);

LocalDateTime d = LocalDateTime.from(z);
System.out.println(d);
}
}

Output

2016-10-12T15:20:30-05:00[America/Chicago]
2016-10-12T15:20:30




package com.logicbig.example.localdatetime;

import java.time.LocalDateTime;

public class FromExample1 {

public static void main (String... args) {
LocalDateTime dt = LocalDateTime.of(2016, 10, 12,
15, 20, 30, 0);
System.out.println(dt);

LocalDateTime d = LocalDateTime.from(dt);
System.out.println(d);
}
}

Output

2016-10-12T15:20:30
2016-10-12T15:20:30




package com.logicbig.example.localdatetime;

import java.time.*;

public class FromExample2 {

public static void main (String... args) {
OffsetDateTime z = OffsetDateTime.of(2016, 10, 12,
15, 20, 30, 0,
ZoneOffset.of("-6"));
System.out.println(z);

LocalDateTime d = LocalDateTime.from(z);
System.out.println(d);
}
}

Output

2016-10-12T15:20:30-06:00
2016-10-12T15:20:30




package com.logicbig.example.localdatetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class FromExample3 {

public static void main (String... args) {
LocalDate d = LocalDate.of(2016, 10, 12);
System.out.println(d);

LocalDateTime dt = LocalDateTime.from(d);
System.out.println(dt);
}
}

Output

Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2016-10-12 of type java.time.LocalDate
at java.time.LocalDateTime.from(LocalDateTime.java:461)
at com.logicbig.example.localdatetime.FromExample3.main(FromExample3.java:19)
... 6 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: 2016-10-12 of type java.time.LocalDate
at java.time.LocalTime.from(LocalTime.java:409)
at java.time.LocalDateTime.from(LocalDateTime.java:457)
... 7 more




See Also