Accessing Fields of Zoned Date-Time

The ZonedDateTime class provides many get methods to access the values of various fields of a zoned date-time. The most versatile is the get(field) method, which supports all the constants defined by the ChronoField enum type (p. 1046). In addition, there are get methods for specific fields, and methods for extracting the different constituent parts of a zoned date-time.

Click here to view code image

// Using ChronoField constants:
int theDay = concertZDT0.get(ChronoField.DAY_OF_MONTH);          // 14
int theMonthValue = concertZDT0.get(ChronoField.MONTH_OF_YEAR);  // 1
int theYear = concertZDT0.get(ChronoField.YEAR);                 // 1973
// Using specific get methods:
int theMonthValue2 = concertZDT0.getMonthValue();                // 1
Month theMonth     = concertZDT0.getMonth();                     // JANUARY
// Extracting constituent parts:
LocalTime theTime     = concertZDT0.toLocalTime();         // 00:10
LocalDate theDate     = concertZDT0.toLocalDate();         // 1973-01-14
LocalDateTime theDT   = concertZDT0.toLocalDateTime();     // 1973-01-14T00:10
ZoneId theZID         = concertZDT0.getZone();             // US/Hawaii
ZoneOffset theZoffset = concertZDT0.getOffset();           // -10:00

int get
FIELD
()

Gets the value of the field designated by the suffix FIELD, which can be DayOf-Month, DayOfYear, MonthValue, Nano, Second, Minute, Hour, or Year.

Click here to view code image

DayOfWeek getDayOfWeek()
Month     getMonth()

Get the value of the day-of-week and month-of-year field, respectively.

ZoneId     getZone()
ZoneOffset getOffset()

Gets the time zone ID (e.g., US/Central) and the time zone offset from UTC/ Greenwich (e.g., -04:00), respectively (p. 1073).

Click here to view code image

int  get(TemporalField field)
long getLong(TemporalField field)
boolean isSupported(TemporalField field)

The first two methods return the value of the specified TemporalField (p. 1046) as an int value or as a long value, respectively. The value of the ChronoField enum constants NANO_OF_DAY, MICRO_OF_DAY, EPOCH_DAY, PROLEPTIC_MONTH, and INSTANT_SECONDS will not fit into an int, and therefore, the getLong() method must be used.

The third method checks if the specified field is supported by this zoned date-time. All ChronoField enum constants are supported by the ZonedDateTime class (p. 1046).

Click here to view code image

LocalTime     toLocalTime()
LocalDate     toLocalDate()
LocalDateTime toLocalDateTime()

Return the respective part of this zoned date-time.

Instant toInstant()

Converts a zoned date-time to an instant representing the same point as this date-time. This method is inherited by the ZonedDateTime class from its super-interface java.time.chrono.ChronoZonedDateTime.

Conversion of a zoned date-time to an instance of the java.util.Date legacy class can be done via this method (p. 1088).

Leave a Reply

Your email address will not be published. Required fields are marked *