OffsetDateTime

Description

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.

Example

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;
/* w  w w  .j  av  a2 s.  c  om*/
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.

Example 2

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;
/*  ww w  . j  a  v  a  2s. 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.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial