Close

Java Date Time - OffsetTime.from() Examples

Java Date Time Java Java API 


Class:

java.time.OffsetTime

java.lang.Objectjava.lang.Objectjava.time.OffsetTimejava.time.OffsetTimejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.lang.ComparableComparablejava.io.SerializableSerializableLogicBig

Method:

public static OffsetTime from(TemporalAccessor temporal)

This static method returns a new OffsetTime instance based on the provided TemporalAccessor.

The provided temporal accessor must have all fields needed for an OffsetTime instance creation, otherwise DateTimeException will be thrown.


Examples


package com.logicbig.example.offsettime;

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

public class FromExample {

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

OffsetTime t = OffsetTime.from(d);
System.out.println(t);
}
}

Output

2017-05-01T16:14:43.630-05:00[America/Chicago]
16:14:43.630-05:00




package com.logicbig.example.offsettime;

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

public class FromExample2 {

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

OffsetTime t = OffsetTime.from(d);
System.out.println(t);
}
}

Output

2017-05-01T16:14:45.715-05:00
16:14:45.715-05:00




package com.logicbig.example.offsettime;

import java.time.LocalTime;
import java.time.OffsetTime;

public class FromExample3 {

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

OffsetTime t = OffsetTime.from(d);
System.out.println(t);
}
}

Output

Caused by: java.time.DateTimeException: Unable to obtain OffsetTime from TemporalAccessor: 16:14:47.763 of type java.time.LocalTime
at java.time.OffsetTime.from(OffsetTime.java:296)
at com.logicbig.example.offsettime.FromExample3.main(FromExample3.java:17)
... 6 more
Caused by: java.time.DateTimeException: Unable to obtain ZoneOffset from TemporalAccessor: 16:14:47.763 of type java.time.LocalTime
at java.time.ZoneOffset.from(ZoneOffset.java:348)
at java.time.OffsetTime.from(OffsetTime.java:292)
... 7 more




See Also