Java Reference
In-Depth Information
Offset Time and Datetime
An instance of the OffsetTime and OffsetDateTime classes represents a time and a datetime, respectively, with a fixed
zone offset from UTC. An offset time and datetime have no knowledge of a time zone. Examples of an offset time and
an offset datetime in the ISO-8601 format are 10:50:11+5:30 and 2012-05-11T10:50:11+5:30, respectively.
Tip
there is no OffsetDate class. it was part of the initial design. Later, it was dropped.
The relationships between local and offset dates and times can be represented as follows:
OffsetTime = LocalTime + ZoneOffset
OffsetDateTime = LocalDateTime + ZoneOffset
Working with an offset time and datetime is similar to working with their local counterparts, except that you have
to use a zone offset. You can always extract a LocalXxx from an OffsetXxx . An OffsetDateTime stores an instant on
the timeline, and hence, conversion between OffsetDateTime and Instant is supported.
Listing 12-8 shows examples of creating offset time and datetime. When you get the current offset time and
datetime using the now() method, the system default time zone is used to obtain the zone offset value. You will get a
different output for current time and datetime.
Listing 12-8. Using Offset Dates, Times, and Datetimes
// OffsetDateTimeTest.java
package com.jdojo.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class OffsetDateTimeTest {
public static void main(String[] args) {
// Get the current offset time
OffsetTime ot1 = OffsetTime.now();
System.out.println("Current offset time: " + ot1);
// Creete a zone offset +05:30
ZoneOffset offset = ZoneOffset.ofHoursMinutes(5, 30);
// Create an offset time
OffsetTime ot2 = OffsetTime.of(16, 40, 28, 0, offset);
System.out.println("An offset time: " + ot2);
// Get the current offset datetime
OffsetDateTime odt1 = OffsetDateTime.now();
System.out.println("Current offset datetime: " + odt1);
 
 
Search WWH ::




Custom Search