Java - Date Time Fields, ChronoField

Introduction

ChronoField enum implements the TemporalField interface and provides several constants to represent fields in a datetime.

ChronoField enum contains a long list of constants. Some of them are as follows:

AMPM_OF_DAY,
CLOCK_HOUR_OF_AMPM, 
CLOCK_HOUR_OF_DAY, 
DAY_OF_MONTH, 
DAY_OF_WEEK, 
DAY_OF_YEAR, 
ERA, 
HOUR_OF_AMPM,
HOUR_OF_DAY, 
INSTANT_SECONDS, 
MINUTE_OF_HOUR, 
MONTH_OF_YEAR, 
SECOND_OF_MINUTE, 
YEAR, 
YEAR_OF_ERA.

The following code demonstrates how to use a ChronoField to extract a field value from a datetime and whether the datetime supported the field:

Demo

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

public class Main {
  public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
    System.out.println("Current Date Time: " + now);
    System.out.println("Year: " + now.get(ChronoField.YEAR));
    System.out.println("Month: " + now.get(ChronoField.MONTH_OF_YEAR));
    System.out.println("Day: " + now.get(ChronoField.DAY_OF_MONTH));
    System.out.println("Hour-of-day: " + now.get(ChronoField.HOUR_OF_DAY));
    System.out.println("Hour-of-AMPM: " + now.get(ChronoField.HOUR_OF_AMPM));
    System.out.println("AMPM-of-day: " + now.get(ChronoField.AMPM_OF_DAY));

    LocalDate today = LocalDate.now();
    System.out.println("Current Date : " + today);
    System.out.println("LocalDate supports year: "
        + today.isSupported(ChronoField.YEAR));
    System.out.println("LocalDate supports hour-of-day: "
        + today.isSupported(ChronoField.HOUR_OF_DAY));

    System.out.println("Year is supported by LocalDate: "
        + ChronoField.YEAR.isSupportedBy(today));
    System.out.println("Hour-of-day is supported by LocalDate: "
        + ChronoField.HOUR_OF_DAY.isSupportedBy(today));
  }//from  ww w . ja  v a  2s .c  o m
}

Result