OffsetTime represents a time with a fixed zone offset from UTC.
OffsetTime combines LocalTime and ZoneOffset.
System default time zone is used to obtain the zone offset value when using now() on offset time.
The following code shows how to create offset time.
import java.time.OffsetTime; import java.time.ZoneOffset; //from ww w. j av a 2 s . co m public class Main { public static void main(String[] args) { // current offset time OffsetTime ot1 = OffsetTime.now(); System.out.println("Current offset time: " + ot1); // a zone offset +01:30 ZoneOffset offset = ZoneOffset.ofHoursMinutes(1, 30); OffsetTime offsetTime = OffsetTime.of(16, 40, 28, 0, offset); System.out.println(offsetTime); } }
The code above generates the following result.
OffsetDateTime represents a datetime, with a fixed zone offset from UTC.
OffsetDateTime combines LocalDateTime and ZoneOffset.
We can extract a Local date and time from an Offset date and time.
System default time zone is used to obtain the zone offset value when using now() on offset date and time.
The following code shows how to create offset datetime.
import java.time.LocalDate; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; /*from w w w. j av a2 s .co m*/ public class Main { public static void main(String[] args) { // Get the current offset datetime OffsetDateTime OffsetDateTime odt1 = OffsetDateTime.now(); // Create an offset datetime OffsetDateTime odt2 = OffsetDateTime.of(2012, 5, 11, 18, 10, 30, 0, ZoneOffset.UTC); // Get the local date and time from the offset datetime LocalDate localDate = odt1.toLocalDate(); LocalTime localTime = odt1.toLocalTime(); System.out.println(localDate); System.out.println(localTime); } }
The code above generates the following result.
The following code shows how to create an offset datetime from the instant.
import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; // w ww .j a va2 s. c o m public class Main { public static void main(String[] args) { Instant i1 = Instant.now(); ZoneId usChicago = ZoneId.of("America/Chicago"); OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(i1, usChicago); System.out.println(offsetDateTime); } }
The code above generates the following result.