Java Date Time - Java Chrono Field Unit








ChronoField

ChronoField enum defines a standard set of fields, such as AMPM_OF_DAY, DAY_OF_MONTH, DAY_OF_WEEK, DAY_OF_YEAR, ERA, HOUR_OF_DAY, MINUTE_OF_HOUR, MONTH_OF_YEAR, SECOND_OF_MINUTE, YEAR, YEAR_OF_ERA.

The following code shows how to use a ChronoField to extract the field value from a datetime.

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
//from   w w w. ja  v a 2  s.  c o  m
public class Main {
  public static void main(String[] args) {
    LocalDateTime  now = LocalDateTime.now(); 
    System.out.println(now.get(ChronoField.YEAR)); 
    System.out.println(now.get(ChronoField.MONTH_OF_YEAR)); 
    System.out.println(now.get(ChronoField.DAY_OF_MONTH)); 
    System.out.println(now.get(ChronoField.HOUR_OF_DAY));
    System.out.println(now.get(ChronoField.HOUR_OF_AMPM)); 
    System.out.println(now.get(ChronoField.AMPM_OF_DAY));

  }
}

The code above generates the following result.





Example 2

The following code shows how to check if a data time object supports a ChronoField.

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
/*from  w  w  w .ja  v a  2s  . c  om*/
public class Main {
  public static void main(String[] args) {
    LocalDateTime  now = LocalDateTime.now(); 
    System.out.println(now.isSupported(ChronoField.YEAR)); 
    System.out.println(now.isSupported(ChronoField.HOUR_OF_DAY));

    System.out.println(ChronoField.YEAR.isSupportedBy(now)); 
    System.out.println(ChronoField.HOUR_OF_DAY.isSupportedBy(now));
  }
}

The code above generates the following result.





ChronoUnit

ChronoUnit enum represents units of time.

It contains the following constants: CENTURIES, DAYS, DECADES, ERAS, FOREVER, HALF_DAYS, HOURS, MICROS, MILLENNIA, MILLIS, MINUTES, MONTHS, NANOS, SECONDS, WEEKS, and YEARS.

The following code shows how to use ChronoUnit enum constants.

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
// w  w w.  ja v a 2 s. c om
public class Main {
  public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();

    // Get the date time 10 days ago
    LocalDateTime localDateTime1 = now.minus(10, ChronoUnit.DAYS);
    System.out.println(localDateTime1);


  }
}

The code above generates the following result.