How do I use TemporalField to access date time value?

The LocalDate and LocalTime are probably the first two classes from the Java 8 Date and Time API that you will work with. An instance of the LocalDate object is an immutable object representing a date without the time of the day and on the other way around the LocalTime object is an immutable object representing a time without the date information.

The LocalDate object have methods to get information related to date such as getYear(), getMonth(), getDayOfMonth(). While the LocalTime object have methods to get information related to time such as getHour(), getMinute(), getSecond(). Beside using those methods we can also access the value of these object using the TemporalField interface. We can pass a TemporalField to the get() method of LocalDate and LocalTime objects. TemporalField is an interface, one of its implementation that we can use to get the value is the ChronoField enumerations.

Let’s see some examples in the code snippet below:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class DateTimeValueTemporalField {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        System.out.println("Date = " + date);
        System.out.println("Year = " + date.getYear());
        System.out.println("Year = " + date.get(ChronoField.YEAR));

        System.out.println("Month= " + date.getMonth().getValue());
        System.out.println("Month= " + date.get(ChronoField.MONTH_OF_YEAR));

        System.out.println("Date = " + date.getDayOfMonth());
        System.out.println("Date = " + date.get(ChronoField.DAY_OF_MONTH));

        System.out.println("DOW  = " + date.getDayOfWeek().getValue());
        System.out.println("DOW  = " + date.get(ChronoField.DAY_OF_WEEK) + "\n");

        LocalTime time = LocalTime.now();
        System.out.println("Time  = " + time);
        System.out.println("Hour  = " + time.getHour());
        System.out.println("Hour  = " + time.get(ChronoField.HOUR_OF_DAY));

        System.out.println("Minute= " + time.getMinute());
        System.out.println("Minute= " + time.get(ChronoField.MINUTE_OF_HOUR));

        System.out.println("Second= " + time.getSecond());
        System.out.println("Second= " + time.get(ChronoField.SECOND_OF_MINUTE));

        System.out.println("Nano  = " + time.getNano());
        System.out.println("Nano  = " + time.get(ChronoField.NANO_OF_SECOND));
    }
}

The output of the code snippet above are:

Date = 2021-11-22
Year = 2021
Year = 2021
Month= 11
Month= 11
Date = 22
Date = 22
DOW  = 1
DOW  = 1

Time  = 10:52:18.082348200
Hour  = 10
Hour  = 10
Minute= 52
Minute= 52
Second= 18
Second= 18
Nano  = 82348200
Nano  = 82348200
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.