Java Data Type How to - Create enum Interval via Duration








Question

We would like to know how to create enum Interval via Duration.

Answer

import java.time.Duration;
/*  www.  j  a  va 2 s .c o m*/
public class Main {

  public static void main(String[] args) {
    Interval i = Interval.ONE_DAY;
    System.out.println(i.getInterval());
    System.out.println(i);
  }

}

enum Interval {
  /**
   * Sets the interval to -1.
   */
  NO_INTERVAL(Duration.ofMillis(-1L)),

  /**
   * Sets the interval to one week (7 days).
   */
  // Note that ChronoUnit.WEEKS is not possible because of DST.
  ONE_WEEK(Duration.ofDays(7)), // 

  /**
   * Sets the interval to one day.
   */
  ONE_DAY(Duration.ofDays(1L)),

  /**
   * Sets the interval to twelve hours.
   */
  TWELVE_HOURS(Duration.ofHours(12L)),

  /**
   * Sets the interval to two hours.
   */
  TWO_HOURS(Duration.ofHours(2L)),

  /**
   * Sets the interval to one hour.
   */
  ONE_HOUR(Duration.ofHours(1L)),

  /**
   * Sets the interval to half an hour.
   */
  HALF_AN_HOUR(Duration.ofMinutes(30L)),

  /**
   * Sets the interval to ten minutes.
   */
  TEN_MINUTES(Duration.ofMinutes(10L)),
  /**
   * Sets the interval to five minutes.
   */
  FIVE_MINUTES(Duration.ofMinutes(5L)),

  /**
   * Sets the interval to one minute.
   */
  ONE_MINUTE(Duration.ofMinutes(1L));

  /**
   * The interval value.
   * 
   * @see #getInterval()
   */
  private Duration interval = Duration.ofMillis(-1L);

  /**
   * Sets the interval to the specified duration.
   * 
   * @param duration the interval
   * @see #getInterval()
   */
  private Interval(Duration duration) {
      this.interval = duration;
  }

  /**
   * Returns the interval duration.
   * 
   * @return this interval
   */
  public Duration getInterval() {
      return interval;
  }
}

The code above generates the following result.