Half.java

  1. /*
  2.  * Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
  3.  *
  4.  * All rights reserved.
  5.  *
  6.  * Redistribution and use in source and binary forms, with or without
  7.  * modification, are permitted provided that the following conditions are met:
  8.  *
  9.  *  * Redistributions of source code must retain the above copyright notice,
  10.  *    this list of conditions and the following disclaimer.
  11.  *
  12.  *  * Redistributions in binary form must reproduce the above copyright notice,
  13.  *    this list of conditions and the following disclaimer in the documentation
  14.  *    and/or other materials provided with the distribution.
  15.  *
  16.  *  * Neither the name of JSR-310 nor the names of its contributors
  17.  *    may be used to endorse or promote products derived from this software
  18.  *    without specific prior written permission.
  19.  *
  20.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23.  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  24.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  25.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  28.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  30.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  */
  32. package org.threeten.extra;

  33. import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  34. import static org.threeten.extra.TemporalFields.HALF_OF_YEAR;
  35. import static org.threeten.extra.TemporalFields.HALF_YEARS;

  36. import java.time.DateTimeException;
  37. import java.time.LocalDate;
  38. import java.time.Month;
  39. import java.time.chrono.Chronology;
  40. import java.time.chrono.IsoChronology;
  41. import java.time.format.DateTimeFormatterBuilder;
  42. import java.time.format.TextStyle;
  43. import java.time.temporal.ChronoField;
  44. import java.time.temporal.Temporal;
  45. import java.time.temporal.TemporalAccessor;
  46. import java.time.temporal.TemporalAdjuster;
  47. import java.time.temporal.TemporalField;
  48. import java.time.temporal.TemporalQueries;
  49. import java.time.temporal.TemporalQuery;
  50. import java.time.temporal.UnsupportedTemporalTypeException;
  51. import java.time.temporal.ValueRange;
  52. import java.util.Locale;

  53. /**
  54.  * A half-of-year, such as 'H2'.
  55.  * <p>
  56.  * {@code Half} is an enum representing the 2 halves of the year - H1 and H2.
  57.  * These are defined as January to June and July to December.
  58.  * <p>
  59.  * The {@code int} value follows the half, from 1 (H1) to 2 (H2).
  60.  * It is recommended that applications use the enum rather than the {@code int} value
  61.  * to ensure code clarity.
  62.  * <p>
  63.  * <b>Do not use {@code ordinal()} to obtain the numeric representation of {@code Half}.
  64.  * Use {@code getValue()} instead.</b>
  65.  *
  66.  * <h3>Implementation Requirements:</h3>
  67.  * This is an immutable and thread-safe enum.
  68.  */
  69. public enum Half implements TemporalAccessor, TemporalAdjuster {

  70.     /**
  71.      * The singleton instance for the first half-of-year, from January to June.
  72.      * This has the numeric value of {@code 1}.
  73.      */
  74.     H1,
  75.     /**
  76.      * The singleton instance for the second half-of-year, from July to December.
  77.      * This has the numeric value of {@code 2}.
  78.      */
  79.     H2;

  80.     //-----------------------------------------------------------------------
  81.     /**
  82.      * Obtains an instance of {@code Half} from an {@code int} value.
  83.      * <p>
  84.      * {@code Half} is an enum representing the 2 halves of the year.
  85.      * This factory allows the enum to be obtained from the {@code int} value.
  86.      * The {@code int} value follows the half, from 1 (H1) to 2 (H2).
  87.      *
  88.      * @param halfOfYear  the half-of-year to represent, from 1 (H1) to 2 (H2)
  89.      * @return the half-of-year, not null
  90.      * @throws DateTimeException if the half-of-year is invalid
  91.      */
  92.     public static Half of(int halfOfYear) {
  93.         switch (halfOfYear) {
  94.             case 1:
  95.                 return H1;
  96.             case 2:
  97.                 return H2;
  98.             default:
  99.                 throw new DateTimeException("Invalid value for Half: " + halfOfYear);
  100.         }
  101.     }

  102.     /**
  103.      * Obtains an instance of {@code Half} from a month-of-year.
  104.      * <p>
  105.      * {@code Half} is an enum representing the 2 halves of the year.
  106.      * This factory allows the enum to be obtained from the {@code Month} value.
  107.      * <p>
  108.      * January to June are H1 and July to December are H2.
  109.      *
  110.      * @param monthOfYear  the month-of-year to convert from, from 1 to 12
  111.      * @return the half-of-year, not null
  112.      * @throws DateTimeException if the month-of-year is invalid
  113.      */
  114.     public static Half ofMonth(int monthOfYear) {
  115.         MONTH_OF_YEAR.range().checkValidValue(monthOfYear, MONTH_OF_YEAR);
  116.         return of(monthOfYear <= 6 ? 1 : 2);
  117.     }

  118.     //-----------------------------------------------------------------------
  119.     /**
  120.      * Obtains an instance of {@code Half} from a temporal object.
  121.      * <p>
  122.      * This obtains a half based on the specified temporal.
  123.      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
  124.      * which this factory converts to an instance of {@code Half}.
  125.      * <p>
  126.      * The conversion extracts the {@link TemporalFields#HALF_OF_YEAR HALF_OF_YEAR} field.
  127.      * The extraction is only permitted if the temporal object has an ISO
  128.      * chronology, or can be converted to a {@code LocalDate}.
  129.      * <p>
  130.      * This method matches the signature of the functional interface {@link TemporalQuery}
  131.      * allowing it to be used in queries via method reference, {@code Half::from}.
  132.      *
  133.      * @param temporal  the temporal-time object to convert, not null
  134.      * @return the half-of-year, not null
  135.      * @throws DateTimeException if unable to convert to a {@code Half}
  136.      */
  137.     public static Half from(TemporalAccessor temporal) {
  138.         if (temporal instanceof Half) {
  139.             return (Half) temporal;
  140.         } else if (temporal instanceof Month) {
  141.             Month month = (Month) temporal;
  142.             return of(month.ordinal() / 6 + 1);
  143.         }
  144.         try {
  145.             TemporalAccessor adjusted =
  146.                     !IsoChronology.INSTANCE.equals(Chronology.from(temporal)) ? LocalDate.from(temporal) : temporal;
  147.             // need to use getLong() as JDK Parsed class get() doesn't work properly
  148.             int qoy = Math.toIntExact(adjusted.getLong(HALF_OF_YEAR));
  149.             return of(qoy);
  150.         } catch (DateTimeException ex) {
  151.             throw new DateTimeException("Unable to obtain Half from TemporalAccessor: " +
  152.                     temporal + " of type " + temporal.getClass().getName(), ex);
  153.         }
  154.     }

  155.     //-----------------------------------------------------------------------
  156.     /**
  157.      * Gets the half-of-year {@code int} value.
  158.      * <p>
  159.      * The values are numbered following the ISO-8601 standard,
  160.      * from 1 (H1) to 2 (H2).
  161.      *
  162.      * @return the half-of-year, from 1 (H1) to 2 (H2)
  163.      */
  164.     public int getValue() {
  165.         return ordinal() + 1;
  166.     }

  167.     //-----------------------------------------------------------------------
  168.     /**
  169.      * Gets the textual representation, such as 'H1' or '4th half'.
  170.      * <p>
  171.      * This returns the textual name used to identify the half-of-year,
  172.      * suitable for presentation to the user.
  173.      * The parameters control the style of the returned text and the locale.
  174.      * <p>
  175.      * If no textual mapping is found then the {@link #getValue() numeric value} is returned.
  176.      *
  177.      * @param style  the length of the text required, not null
  178.      * @param locale  the locale to use, not null
  179.      * @return the text value of the half-of-year, not null
  180.      */
  181.     public String getDisplayName(TextStyle style, Locale locale) {
  182.         return new DateTimeFormatterBuilder().appendText(HALF_OF_YEAR, style).toFormatter(locale).format(this);
  183.     }

  184.     //-----------------------------------------------------------------------
  185.     /**
  186.      * Checks if the specified field is supported.
  187.      * <p>
  188.      * This checks if this half-of-year can be queried for the specified field.
  189.      * If false, then calling the {@link #range(TemporalField) range} and
  190.      * {@link #get(TemporalField) get} methods will throw an exception.
  191.      * <p>
  192.      * If the field is {@link TemporalFields#HALF_OF_YEAR HALF_OF_YEAR} then
  193.      * this method returns true.
  194.      * All {@code ChronoField} instances will return false.
  195.      * <p>
  196.      * If the field is not a {@code ChronoField}, then the result of this method
  197.      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
  198.      * passing {@code this} as the argument.
  199.      * Whether the field is supported is determined by the field.
  200.      *
  201.      * @param field  the field to check, null returns false
  202.      * @return true if the field is supported on this half-of-year, false if not
  203.      */
  204.     @Override
  205.     public boolean isSupported(TemporalField field) {
  206.         if (field == HALF_OF_YEAR) {
  207.             return true;
  208.         } else if (field instanceof ChronoField) {
  209.             return false;
  210.         }
  211.         return field != null && field.isSupportedBy(this);
  212.     }

  213.     /**
  214.      * Gets the range of valid values for the specified field.
  215.      * <p>
  216.      * The range object expresses the minimum and maximum valid values for a field.
  217.      * This half is used to enhance the accuracy of the returned range.
  218.      * If it is not possible to return the range, because the field is not supported
  219.      * or for some other reason, an exception is thrown.
  220.      * <p>
  221.      * If the field is {@link TemporalFields#HALF_OF_YEAR HALF_OF_YEAR} then the
  222.      * range of the half-of-year, from 1 to 2, will be returned.
  223.      * All {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
  224.      * <p>
  225.      * If the field is not a {@code ChronoField}, then the result of this method
  226.      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
  227.      * passing {@code this} as the argument.
  228.      * Whether the range can be obtained is determined by the field.
  229.      *
  230.      * @param field  the field to query the range for, not null
  231.      * @return the range of valid values for the field, not null
  232.      * @throws DateTimeException if the range for the field cannot be obtained
  233.      * @throws UnsupportedTemporalTypeException if the field is not supported
  234.      */
  235.     @Override
  236.     public ValueRange range(TemporalField field) {
  237.         if (field == HALF_OF_YEAR) {
  238.             return field.range();
  239.         } else if (field instanceof ChronoField) {
  240.             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
  241.         }
  242.         return TemporalAccessor.super.range(field);
  243.     }

  244.     /**
  245.      * Gets the value of the specified field from this half-of-year as an {@code int}.
  246.      * <p>
  247.      * This queries this half for the value for the specified field.
  248.      * The returned value will always be within the valid range of values for the field.
  249.      * If it is not possible to return the value, because the field is not supported
  250.      * or for some other reason, an exception is thrown.
  251.      * <p>
  252.      * If the field is {@link TemporalFields#HALF_OF_YEAR HALF_OF_YEAR} then the
  253.      * value of the half-of-year, from 1 to 2, will be returned.
  254.      * All {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
  255.      * <p>
  256.      * If the field is not a {@code ChronoField}, then the result of this method
  257.      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
  258.      * passing {@code this} as the argument. Whether the value can be obtained,
  259.      * and what the value represents, is determined by the field.
  260.      *
  261.      * @param field  the field to get, not null
  262.      * @return the value for the field, within the valid range of values
  263.      * @throws DateTimeException if a value for the field cannot be obtained or
  264.      *         the value is outside the range of valid values for the field
  265.      * @throws UnsupportedTemporalTypeException if the field is not supported or
  266.      *         the range of values exceeds an {@code int}
  267.      * @throws ArithmeticException if numeric overflow occurs
  268.      */
  269.     @Override
  270.     public int get(TemporalField field) {
  271.         if (field == HALF_OF_YEAR) {
  272.             return getValue();
  273.         } else if (field instanceof ChronoField) {
  274.             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
  275.         }
  276.         return TemporalAccessor.super.get(field);
  277.     }

  278.     /**
  279.      * Gets the value of the specified field from this half-of-year as a {@code long}.
  280.      * <p>
  281.      * This queries this half for the value for the specified field.
  282.      * If it is not possible to return the value, because the field is not supported
  283.      * or for some other reason, an exception is thrown.
  284.      * <p>
  285.      * If the field is {@link TemporalFields#HALF_OF_YEAR HALF_OF_YEAR} then the
  286.      * value of the half-of-year, from 1 to 2, will be returned.
  287.      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
  288.      * <p>
  289.      * If the field is not a {@code ChronoField}, then the result of this method
  290.      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
  291.      * passing {@code this} as the argument. Whether the value can be obtained,
  292.      * and what the value represents, is determined by the field.
  293.      *
  294.      * @param field  the field to get, not null
  295.      * @return the value for the field
  296.      * @throws DateTimeException if a value for the field cannot be obtained
  297.      * @throws UnsupportedTemporalTypeException if the field is not supported
  298.      * @throws ArithmeticException if numeric overflow occurs
  299.      */
  300.     @Override
  301.     public long getLong(TemporalField field) {
  302.         if (field == HALF_OF_YEAR) {
  303.             return getValue();
  304.         } else if (field instanceof ChronoField) {
  305.             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
  306.         }
  307.         return field.getFrom(this);
  308.     }

  309.     //-----------------------------------------------------------------------
  310.     /**
  311.      * Returns the half that is the specified number of halves after this one.
  312.      * <p>
  313.      * The calculation rolls around the end of the year from H2 to H1.
  314.      * The specified period may be negative.
  315.      * <p>
  316.      * This instance is immutable and unaffected by this method call.
  317.      *
  318.      * @param halves  the halves to add, positive or negative
  319.      * @return the resulting half, not null
  320.      */
  321.     public Half plus(long halves) {
  322.         int amount = (int) halves % 2;
  323.         return values()[(ordinal() + (amount + 2)) % 2];
  324.     }

  325.     /**
  326.      * Returns the half that is the specified number of halves before this one.
  327.      * <p>
  328.      * The calculation rolls around the start of the year from H1 to H2.
  329.      * The specified period may be negative.
  330.      * <p>
  331.      * This instance is immutable and unaffected by this method call.
  332.      *
  333.      * @param halves  the halves to subtract, positive or negative
  334.      * @return the resulting half, not null
  335.      */
  336.     public Half minus(long halves) {
  337.         return plus(-(halves % 2));
  338.     }

  339.     //-----------------------------------------------------------------------
  340.     /**
  341.      * Gets the length of this half in days.
  342.      * <p>
  343.      * This takes a flag to determine whether to return the length for a leap year or not.
  344.      * <p>
  345.      * H1 has 181 in a standard year and 182 days in a leap year.
  346.      * H2 has 184 days.
  347.      *
  348.      * @param leapYear  true if the length is required for a leap year
  349.      * @return the length of this month in days, 181, 182 or 184
  350.      */
  351.     public int length(boolean leapYear) {
  352.         return this == H1 ? (leapYear ? 182 : 181) : 184;
  353.     }

  354.     //-----------------------------------------------------------------------
  355.     /**
  356.      * Gets the first of the six months that this half refers to.
  357.      * <p>
  358.      * H1 will return January.<br>
  359.      * H2 will return July.
  360.      *
  361.      * @return the first month in the half, not null
  362.      */
  363.     public Month firstMonth() {
  364.         return this == H1 ? Month.JANUARY : Month.JULY;
  365.     }

  366.     //-----------------------------------------------------------------------
  367.     /**
  368.      * Queries this half-of-year using the specified query.
  369.      * <p>
  370.      * This queries this half-of-year using the specified query strategy object.
  371.      * The {@code TemporalQuery} object defines the logic to be used to
  372.      * obtain the result. Read the documentation of the query to understand
  373.      * what the result of this method will be.
  374.      * <p>
  375.      * The result of this method is obtained by invoking the
  376.      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
  377.      * specified query passing {@code this} as the argument.
  378.      *
  379.      * @param <R> the type of the result
  380.      * @param query  the query to invoke, not null
  381.      * @return the query result, null may be returned (defined by the query)
  382.      * @throws DateTimeException if unable to query (defined by the query)
  383.      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
  384.      */
  385.     @SuppressWarnings("unchecked")
  386.     @Override
  387.     public <R> R query(TemporalQuery<R> query) {
  388.         if (query == TemporalQueries.chronology()) {
  389.             return (R) IsoChronology.INSTANCE;
  390.         } else if (query == TemporalQueries.precision()) {
  391.             return (R) HALF_YEARS;
  392.         }
  393.         return TemporalAccessor.super.query(query);
  394.     }

  395.     /**
  396.      * Adjusts the specified temporal object to have this half-of-year.
  397.      * <p>
  398.      * This returns a temporal object of the same observable type as the input
  399.      * with the half-of-year changed to be the same as this.
  400.      * <p>
  401.      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
  402.      * passing {@link TemporalFields#HALF_OF_YEAR} as the field.
  403.      * If the specified temporal object does not use the ISO calendar system then
  404.      * a {@code DateTimeException} is thrown.
  405.      * <p>
  406.      * In most cases, it is clearer to reverse the calling pattern by using
  407.      * {@link Temporal#with(TemporalAdjuster)}:
  408.      * <pre>
  409.      *   // these two lines are equivalent, but the second approach is recommended
  410.      *   temporal = thisHalf.adjustInto(temporal);
  411.      *   temporal = temporal.with(thisHalf);
  412.      * </pre>
  413.      * <p>
  414.      * For example, given a date in May, the following are output:
  415.      * <pre>
  416.      *   dateInMay.with(H1);    // no change
  417.      *   dateInMay.with(H2);    // six months later
  418.      * </pre>
  419.      * <p>
  420.      * This instance is immutable and unaffected by this method call.
  421.      *
  422.      * @param temporal  the target object to be adjusted, not null
  423.      * @return the adjusted object, not null
  424.      * @throws DateTimeException if unable to make the adjustment
  425.      * @throws ArithmeticException if numeric overflow occurs
  426.      */
  427.     @Override
  428.     public Temporal adjustInto(Temporal temporal) {
  429.         if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
  430.             throw new DateTimeException("Adjustment only supported on ISO date-time");
  431.         }
  432.         return temporal.with(HALF_OF_YEAR, getValue());
  433.     }

  434. }