Close

Java Date Time - ZonedDateTime.from() Examples

Java Date Time Java Java API 


Class:

java.time.ZonedDateTime

java.lang.Objectjava.lang.Objectjava.time.ZonedDateTimejava.time.ZonedDateTimejava.time.temporal.TemporalTemporaljava.time.chrono.ChronoZonedDateTimeChronoZonedDateTimejava.io.SerializableSerializableLogicBig

Method:

public static ZonedDateTime from(TemporalAccessor temporal)

This static method returns the ZonedDateTime instance based on the provided TemporalAccessor.

The provided temporal accessor must have all fields needed for the OffsetDateTime instance creation otherwise DateTimeException will be thrown.


Examples


package com.logicbig.example.zoneddatetime;

import java.time.OffsetDateTime;
import java.time.ZonedDateTime;

public class FromExample {

public static void main(String... args) {
OffsetDateTime date = OffsetDateTime.now();
System.out.println(date);

ZonedDateTime zdt = ZonedDateTime.from(date);
System.out.println(zdt);
}
}

Output

2017-05-01T16:12:36.432-05:00
2017-05-01T16:12:36.432-05:00




package com.logicbig.example.zoneddatetime;

import java.time.ZonedDateTime;

public class FromExample2 {

public static void main(String... args) {
ZonedDateTime date = ZonedDateTime.now();
System.out.println(date);

ZonedDateTime zdt = ZonedDateTime.from(date);
System.out.println(zdt);
}
}

Output

2017-05-01T16:12:38.508-05:00[America/Chicago]
2017-05-01T16:12:38.508-05:00[America/Chicago]




package com.logicbig.example.zoneddatetime;

import java.time.OffsetTime;
import java.time.ZonedDateTime;

public class FromExample3 {

public static void main(String... args) {
OffsetTime date = OffsetTime.now();
System.out.println(date);

ZonedDateTime zdt = ZonedDateTime.from(date);
System.out.println(zdt);
}
}

Output

Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 16:12:40.541-05:00 of type java.time.OffsetTime
at java.time.ZonedDateTime.from(ZonedDateTime.java:565)
at com.logicbig.example.zoneddatetime.FromExample3.main(FromExample3.java:17)
... 6 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 16:12:40.541-05:00 of type java.time.OffsetTime
at java.time.LocalDate.from(LocalDate.java:368)
at java.time.ZonedDateTime.from(ZonedDateTime.java:559)
... 7 more




See Also