Java - Datetime Field Units, ChronoUnit

Introduction

ChronoUnit contains the following constants to represent units of time:

CENTURIES, 
DAYS, 
DECADES, 
ERAS, 
FOREVER,
HALF_DAYS, 
HOURS, 
MICROS, 
MILLENNIA, 
MILLIS, 
MINUTES, 
MONTHS, 
NANOS, 
SECONDS, 
WEEKS, and 
YEARS.

ChronoUnit enum implements the TemporalUnit interface. Therefore, all constants in the enum are an instance of the TemporalUnit.

Date time classes provide two methods, minus() and plus().

They take an amount of time and the unit of time to return a new date time by subtracting and adding the specified time.

Methods such as minusDays(), minusHours(), plusDays(), plusHours(), etc. are also provided by the some classes to subtract and add time.

The following snippet of code illustrates the use of the ChronoUnit enum constants with these methods:

Demo

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Main {
  public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();

    // Get the date time 4 days ago
    LocalDateTime ldt2 = now.minus(4, ChronoUnit.DAYS);

    // Use the minusDays() method to get the same result
    LocalDateTime ldt3 = now.minusDays(4);

    // Get date and time 4 hours later
    LocalDateTime ldt4 = now.plus(4, ChronoUnit.HOURS);

    // Use the plusHours() method to get the same result
    LocalDateTime ldt5 = now.plusHours(4);

    System.out.println("Current Datetime: " + now);
    System.out.println("4 days ago: " + ldt2);
    System.out.println("4 days ago: " + ldt3);
    System.out.println("4 hours after: " + ldt4);
    System.out.println("4 hours after: " + ldt5);
  }/*  ww w .ja v  a  2s. com*/
}

Result