TimeComponents.java

  1. /* Copyright 2002-2020 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.time;

  18. import java.io.Serializable;
  19. import java.text.DecimalFormat;
  20. import java.text.DecimalFormatSymbols;
  21. import java.util.Locale;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;

  24. import org.hipparchus.util.FastMath;
  25. import org.orekit.errors.OrekitIllegalArgumentException;
  26. import org.orekit.errors.OrekitMessages;
  27. import org.orekit.utils.Constants;


  28. /** Class representing a time within the day broken up as hour,
  29.  * minute and second components.
  30.  * <p>Instances of this class are guaranteed to be immutable.</p>
  31.  * @see DateComponents
  32.  * @see DateTimeComponents
  33.  * @author Luc Maisonobe
  34.  */
  35. public class TimeComponents implements Serializable, Comparable<TimeComponents> {

  36.     /** Constant for commonly used hour 00:00:00. */
  37.     public static final TimeComponents H00   = new TimeComponents(0, 0, 0);

  38.     /** Constant for commonly used hour 12:00:00. */
  39.     public static final TimeComponents H12 = new TimeComponents(12, 0, 0);

  40.     /** Serializable UID. */
  41.     private static final long serialVersionUID = 20160331L;

  42.     /** Format for hours and minutes. */
  43.     private static final DecimalFormat TWO_DIGITS = new DecimalFormat("00");

  44.     /** Format for seconds. */
  45.     private static final DecimalFormat SECONDS_FORMAT =
  46.         new DecimalFormat("00.000", new DecimalFormatSymbols(Locale.US));

  47.     /** Basic and extends formats for local time, with optional timezone. */
  48.     private static final Pattern ISO8601_FORMATS = Pattern.compile("^(\\d\\d):?(\\d\\d):?(\\d\\d(?:[.,]\\d+)?)?(?:Z|([-+]\\d\\d(?::?\\d\\d)?))?$");

  49.     /** Hour number. */
  50.     private final int hour;

  51.     /** Minute number. */
  52.     private final int minute;

  53.     /** Second number. */
  54.     private final double second;

  55.     /** Offset between the specified date and UTC.
  56.      * <p>
  57.      * Always an integral number of minutes, as per ISO-8601 standard.
  58.      * </p>
  59.      * @since 7.2
  60.      */
  61.     private final int minutesFromUTC;

  62.     /** Build a time from its clock elements.
  63.      * <p>Note that seconds between 60.0 (inclusive) and 61.0 (exclusive) are allowed
  64.      * in this method, since they do occur during leap seconds introduction
  65.      * in the {@link UTCScale UTC} time scale.</p>
  66.      * @param hour hour number from 0 to 23
  67.      * @param minute minute number from 0 to 59
  68.      * @param second second number from 0.0 to 61.0 (excluded)
  69.      * @exception IllegalArgumentException if inconsistent arguments
  70.      * are given (parameters out of range)
  71.      */
  72.     public TimeComponents(final int hour, final int minute, final double second)
  73.         throws IllegalArgumentException {
  74.         this(hour, minute, second, 0);
  75.     }

  76.     /** Build a time from its clock elements.
  77.      * <p>Note that seconds between 60.0 (inclusive) and 61.0 (exclusive) are allowed
  78.      * in this method, since they do occur during leap seconds introduction
  79.      * in the {@link UTCScale UTC} time scale.</p>
  80.      * @param hour hour number from 0 to 23
  81.      * @param minute minute number from 0 to 59
  82.      * @param second second number from 0.0 to 61.0 (excluded)
  83.      * @param minutesFromUTC offset between the specified date and UTC, as an
  84.      * integral number of minutes, as per ISO-8601 standard
  85.      * @exception IllegalArgumentException if inconsistent arguments
  86.      * are given (parameters out of range)
  87.      * @since 7.2
  88.      */
  89.     public TimeComponents(final int hour, final int minute, final double second,
  90.                           final int minutesFromUTC)
  91.         throws IllegalArgumentException {

  92.         // range check
  93.         if ((hour   < 0) || (hour   >  23) ||
  94.             (minute < 0) || (minute >  59) ||
  95.             (second < 0) || (second >= 61.0)) {
  96.             throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_HMS_TIME,
  97.                                                      hour, minute, second);
  98.         }

  99.         this.hour           = hour;
  100.         this.minute         = minute;
  101.         this.second         = second;
  102.         this.minutesFromUTC = minutesFromUTC;

  103.     }

  104.     /**
  105.      * Build a time from the second number within the day.
  106.      *
  107.      * <p>If the {@code secondInDay} is less than {@code 60.0} then {@link #getSecond()}
  108.      * will be less than {@code 60.0}, otherwise it will be less than {@code 61.0}. This constructor
  109.      * may produce an invalid value of {@link #getSecond()} during a negative leap second,
  110.      * through there has never been one. For more control over the number of seconds in
  111.      * the final minute use {@link #fromSeconds(int, double, double, int)}.
  112.      *
  113.      * <p>This constructor is always in UTC (i.e. {@link #getMinutesFromUTC() will return
  114.      * 0}).
  115.      *
  116.      * @param secondInDay second number from 0.0 to {@link Constants#JULIAN_DAY} {@code +
  117.      *                    1} (excluded)
  118.      * @throws OrekitIllegalArgumentException if seconds number is out of range
  119.      * @see #fromSeconds(int, double, double, int)
  120.      * @see #TimeComponents(int, double)
  121.      */
  122.     public TimeComponents(final double secondInDay)
  123.             throws OrekitIllegalArgumentException {
  124.         this(0, secondInDay);
  125.     }

  126.     /**
  127.      * Build a time from the second number within the day.
  128.      *
  129.      * <p>The second number is defined here as the sum
  130.      * {@code secondInDayA + secondInDayB} from 0.0 to {@link Constants#JULIAN_DAY}
  131.      * {@code + 1} (excluded). The two parameters are used for increased accuracy.
  132.      *
  133.      * <p>If the sum is less than {@code 60.0} then {@link #getSecond()} will be less
  134.      * than {@code 60.0}, otherwise it will be less than {@code 61.0}. This constructor
  135.      * may produce an invalid value of {@link #getSecond()} during a negative leap second,
  136.      * through there has never been one. For more control over the number of seconds in
  137.      * the final minute use {@link #fromSeconds(int, double, double, int)}.
  138.      *
  139.      * <p>This constructor is always in UTC (i.e. {@link #getMinutesFromUTC()} will
  140.      * return 0).
  141.      *
  142.      * @param secondInDayA first part of the second number
  143.      * @param secondInDayB last part of the second number
  144.      * @throws OrekitIllegalArgumentException if seconds number is out of range
  145.      * @see #fromSeconds(int, double, double, int)
  146.      */
  147.     public TimeComponents(final int secondInDayA, final double secondInDayB)
  148.             throws OrekitIllegalArgumentException {
  149.         // if the total is at least 86400 then assume there is a leap second
  150.         this(
  151.                 (Constants.JULIAN_DAY - secondInDayA) - secondInDayB > 0 ? secondInDayA : secondInDayA - 1,
  152.                 secondInDayB,
  153.                 (Constants.JULIAN_DAY - secondInDayA) - secondInDayB > 0 ? 0 : 1,
  154.                 (Constants.JULIAN_DAY - secondInDayA) - secondInDayB > 0 ? 60 : 61);
  155.     }

  156.     /**
  157.      * Build a time from the second number within the day.
  158.      *
  159.      * <p>The seconds past midnight is the sum {@code secondInDayA + secondInDayB +
  160.      * leap}. The two parameters are used for increased accuracy. Only the first part of
  161.      * the sum ({@code secondInDayA + secondInDayB}) is used to compute the hours and
  162.      * minutes. The third parameter ({@code leap}) is added directly to the second value
  163.      * ({@link #getSecond()}) to implement leap seconds. These three quantities must
  164.      * satisfy the following constraints. This first guarantees the hour and minute are
  165.      * valid, the second guarantees the second is valid.
  166.      *
  167.      * <pre>
  168.      *     {@code 0 <= secondInDayA + secondInDayB < 86400}
  169.      *     {@code 0 <= (secondInDayA + secondInDayB) % 60 + leap < minuteDuration}
  170.      *     {@code 0 <= leap <= minuteDuration - 60                        if minuteDuration >= 60}
  171.      *     {@code 0 >= leap >= minuteDuration - 60                        if minuteDuration <  60}
  172.      * </pre>
  173.      *
  174.      * <p>If the seconds of minute ({@link #getSecond()}) computed from {@code
  175.      * secondInDayA + secondInDayB + leap} is greater than or equal to {@code
  176.      * minuteDuration} then the second of minute will be set to {@code
  177.      * FastMath.nextDown(minuteDuration)}. This prevents rounding to an invalid seconds of
  178.      * minute number when the input values have greater precision than a {@code double}.
  179.      *
  180.      * <p>This constructor is always in UTC (i.e. {@link #getMinutesFromUTC() will return
  181.      * 0}).
  182.      *
  183.      * <p>If {@code secondsInDayB} or {@code leap} is NaN then the hour and minute will
  184.      * be determined from {@code secondInDayA} and the second of minute will be NaN.
  185.      *
  186.      * <p>This constructor is private to avoid confusion with the other constructors that
  187.      * would be caused by overloading. Use {@link #fromSeconds(int, double, double,
  188.      * int)}.
  189.      *
  190.      * @param secondInDayA   first part of the second number.
  191.      * @param secondInDayB   last part of the second number.
  192.      * @param leap           magnitude of the leap second if this point in time is during
  193.      *                       a leap second, otherwise {@code 0.0}. This value is not used
  194.      *                       to compute hours and minutes, but it is added to the computed
  195.      *                       second of minute.
  196.      * @param minuteDuration number of seconds in the current minute, normally {@code 60}.
  197.      * @throws OrekitIllegalArgumentException if the inequalities above do not hold.
  198.      * @see #fromSeconds(int, double, double, int)
  199.      * @since 10.2
  200.      */
  201.     private TimeComponents(final int secondInDayA,
  202.                            final double secondInDayB,
  203.                            final double leap,
  204.                            final int minuteDuration) throws OrekitIllegalArgumentException {

  205.         // split the numbers as a whole number of seconds
  206.         // and a fractional part between 0.0 (included) and 1.0 (excluded)
  207.         final int carry         = (int) FastMath.floor(secondInDayB);
  208.         int wholeSeconds        = secondInDayA + carry;
  209.         final double fractional = secondInDayB - carry;

  210.         // range check
  211.         if (wholeSeconds < 0 || wholeSeconds >= Constants.JULIAN_DAY) {
  212.             throw new OrekitIllegalArgumentException(
  213.                     OrekitMessages.OUT_OF_RANGE_SECONDS_NUMBER_DETAIL,
  214.                     // this can produce some strange messages due to rounding
  215.                     secondInDayA + secondInDayB,
  216.                     0,
  217.                     Constants.JULIAN_DAY);
  218.         }
  219.         final int maxExtraSeconds = minuteDuration - 60;
  220.         if (leap * maxExtraSeconds < 0 ||
  221.                 FastMath.abs(leap) > FastMath.abs(maxExtraSeconds)) {
  222.             throw new OrekitIllegalArgumentException(
  223.                     OrekitMessages.OUT_OF_RANGE_SECONDS_NUMBER_DETAIL,
  224.                     leap, 0, maxExtraSeconds);
  225.         }

  226.         // extract the time components
  227.         hour           = wholeSeconds / 3600;
  228.         wholeSeconds  -= 3600 * hour;
  229.         minute         = wholeSeconds / 60;
  230.         wholeSeconds  -= 60 * minute;
  231.         // at this point ((minuteDuration - wholeSeconds) - leap) - fractional > 0
  232.         // or else one of the preconditions was violated. Even if there is not violation,
  233.         // naiveSecond may round to minuteDuration, creating an invalid time.
  234.         // In that case round down to preserve a valid time at the cost of up to 1 ULP of error.
  235.         // See #676 and #681.
  236.         final double naiveSecond = wholeSeconds + (leap + fractional);
  237.         if (naiveSecond < 0) {
  238.             throw new OrekitIllegalArgumentException(
  239.                     OrekitMessages.OUT_OF_RANGE_SECONDS_NUMBER_DETAIL,
  240.                     naiveSecond, 0, minuteDuration);
  241.         }
  242.         if (naiveSecond < minuteDuration || Double.isNaN(naiveSecond)) {
  243.             second = naiveSecond;
  244.         } else {
  245.             second = FastMath.nextDown((double) minuteDuration);
  246.         }
  247.         minutesFromUTC = 0;

  248.     }

  249.     /**
  250.      * Build a time from the second number within the day.
  251.      *
  252.      * <p>The seconds past midnight is the sum {@code secondInDayA + secondInDayB +
  253.      * leap}. The two parameters are used for increased accuracy. Only the first part of
  254.      * the sum ({@code secondInDayA + secondInDayB}) is used to compute the hours and
  255.      * minutes. The third parameter ({@code leap}) is added directly to the second value
  256.      * ({@link #getSecond()}) to implement leap seconds. These three quantities must
  257.      * satisfy the following constraints. This first guarantees the hour and minute are
  258.      * valid, the second guarantees the second is valid.
  259.      *
  260.      * <pre>
  261.      *     {@code 0 <= secondInDayA + secondInDayB < 86400}
  262.      *     {@code 0 <= (secondInDayA + secondInDayB) % 60 + leap <= minuteDuration}
  263.      *     {@code 0 <= leap <= minuteDuration - 60                        if minuteDuration >= 60}
  264.      *     {@code 0 >= leap >= minuteDuration - 60                        if minuteDuration <  60}
  265.      * </pre>
  266.      *
  267.      * <p>If the seconds of minute ({@link #getSecond()}) computed from {@code
  268.      * secondInDayA + secondInDayB + leap} is greater than or equal to {@code 60 + leap}
  269.      * then the second of minute will be set to {@code FastMath.nextDown(60 + leap)}. This
  270.      * prevents rounding to an invalid seconds of minute number when the input values have
  271.      * greater precision than a {@code double}.
  272.      *
  273.      * <p>This constructor is always in UTC (i.e. {@link #getMinutesFromUTC() will return
  274.      * 0}).
  275.      *
  276.      * <p>If {@code secondsInDayB} or {@code leap} is NaN then the hour and minute will
  277.      * be determined from {@code secondInDayA} and the second of minute will be NaN.
  278.      *
  279.      * @param secondInDayA   first part of the second number.
  280.      * @param secondInDayB   last part of the second number.
  281.      * @param leap           magnitude of the leap second if this point in time is during
  282.      *                       a leap second, otherwise {@code 0.0}. This value is not used
  283.      *                       to compute hours and minutes, but it is added to the computed
  284.      *                       second of minute.
  285.      * @param minuteDuration number of seconds in the current minute, normally {@code 60}.
  286.      * @return new time components for the specified time.
  287.      * @throws OrekitIllegalArgumentException if the inequalities above do not hold.
  288.      * @since 10.2
  289.      */
  290.     public static TimeComponents fromSeconds(final int secondInDayA,
  291.                                              final double secondInDayB,
  292.                                              final double leap,
  293.                                              final int minuteDuration) {
  294.         return new TimeComponents(secondInDayA, secondInDayB, leap, minuteDuration);
  295.     }

  296.     /** Parse a string in ISO-8601 format to build a time.
  297.      * <p>The supported formats are:
  298.      * <ul>
  299.      *   <li>basic and extended format local time: hhmmss, hh:mm:ss (with optional decimals in seconds)</li>
  300.      *   <li>optional UTC time: hhmmssZ, hh:mm:ssZ</li>
  301.      *   <li>optional signed hours UTC offset: hhmmss+HH, hhmmss-HH, hh:mm:ss+HH, hh:mm:ss-HH</li>
  302.      *   <li>optional signed basic hours and minutes UTC offset: hhmmss+HHMM, hhmmss-HHMM, hh:mm:ss+HHMM, hh:mm:ss-HHMM</li>
  303.      *   <li>optional signed extended hours and minutes UTC offset: hhmmss+HH:MM, hhmmss-HH:MM, hh:mm:ss+HH:MM, hh:mm:ss-HH:MM</li>
  304.      * </ul>
  305.      *
  306.      * <p> As shown by the list above, only the complete representations defined in section 4.2
  307.      * of ISO-8601 standard are supported, neither expended representations nor representations
  308.      * with reduced accuracy are supported.
  309.      *
  310.      * @param string string to parse
  311.      * @return a parsed time
  312.      * @exception IllegalArgumentException if string cannot be parsed
  313.      */
  314.     public static TimeComponents parseTime(final String string) {

  315.         // is the date a calendar date ?
  316.         final Matcher timeMatcher = ISO8601_FORMATS.matcher(string);
  317.         if (timeMatcher.matches()) {
  318.             final int    hour      = Integer.parseInt(timeMatcher.group(1));
  319.             final int    minute    = Integer.parseInt(timeMatcher.group(2));
  320.             final double second    = timeMatcher.group(3) == null ? 0.0 : Double.parseDouble(timeMatcher.group(3).replace(',', '.'));
  321.             final String offset    = timeMatcher.group(4);
  322.             final int    minutesFromUTC;
  323.             if (offset == null) {
  324.                 // no offset from UTC is given
  325.                 minutesFromUTC = 0;
  326.             } else {
  327.                 // we need to parse an offset from UTC
  328.                 // the sign is mandatory and the ':' separator is optional
  329.                 // so we can have offsets given as -06:00 or +0100
  330.                 final int sign          = offset.codePointAt(0) == '-' ? -1 : +1;
  331.                 final int hourOffset    = Integer.parseInt(offset.substring(1, 3));
  332.                 final int minutesOffset = offset.length() <= 3 ? 0 : Integer.parseInt(offset.substring(offset.length() - 2));
  333.                 minutesFromUTC          = sign * (minutesOffset + 60 * hourOffset);
  334.             }
  335.             return new TimeComponents(hour, minute, second, minutesFromUTC);
  336.         }

  337.         throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_TIME, string);

  338.     }

  339.     /** Get the hour number.
  340.      * @return hour number from 0 to 23
  341.      */
  342.     public int getHour() {
  343.         return hour;
  344.     }

  345.     /** Get the minute number.
  346.      * @return minute minute number from 0 to 59
  347.      */
  348.     public int getMinute() {
  349.         return minute;
  350.     }

  351.     /** Get the seconds number.
  352.      * @return second second number from 0.0 to 61.0 (excluded). Note that 60 &le; second
  353.      * &lt; 61 only occurs during a leap second.
  354.      */
  355.     public double getSecond() {
  356.         return second;
  357.     }

  358.     /** Get the offset between the specified date and UTC.
  359.      * <p>
  360.      * The offset is always an integral number of minutes, as per ISO-8601 standard.
  361.      * </p>
  362.      * @return offset in minutes between the specified date and UTC
  363.      * @since 7.2
  364.      */
  365.     public int getMinutesFromUTC() {
  366.         return minutesFromUTC;
  367.     }

  368.     /** Get the second number within the local day, <em>without</em> applying the {@link #getMinutesFromUTC() offset from UTC}.
  369.      * @return second number from 0.0 to Constants.JULIAN_DAY
  370.      * @see #getSecondsInUTCDay()
  371.      * @since 7.2
  372.      */
  373.     public double getSecondsInLocalDay() {
  374.         return second + 60 * minute + 3600 * hour;
  375.     }

  376.     /** Get the second number within the UTC day, applying the {@link #getMinutesFromUTC() offset from UTC}.
  377.      * @return second number from {@link #getMinutesFromUTC() -getMinutesFromUTC()}
  378.      * to Constants.JULIAN_DAY {@link #getMinutesFromUTC() + getMinutesFromUTC()}
  379.      * @see #getSecondsInLocalDay()
  380.      * @since 7.2
  381.      */
  382.     public double getSecondsInUTCDay() {
  383.         return second + 60 * (minute - minutesFromUTC) + 3600 * hour;
  384.     }

  385.     /** Get a string representation of the time.
  386.      * @return string representation of the time
  387.      */
  388.     public String toString() {
  389.         StringBuilder builder  = new StringBuilder().
  390.                                  append(TWO_DIGITS.format(hour)).append(':').
  391.                                  append(TWO_DIGITS.format(minute)).append(':').
  392.                                  append(SECONDS_FORMAT.format(second));
  393.         if (minutesFromUTC != 0) {
  394.             builder = builder.
  395.                       append(minutesFromUTC < 0 ? '-' : '+').
  396.                       append(TWO_DIGITS.format(FastMath.abs(minutesFromUTC) / 60)).append(':').
  397.                       append(TWO_DIGITS.format(FastMath.abs(minutesFromUTC) % 60));
  398.         }
  399.         return builder.toString();
  400.     }

  401.     /** {@inheritDoc} */
  402.     public int compareTo(final TimeComponents other) {
  403.         return Double.compare(getSecondsInUTCDay(), other.getSecondsInUTCDay());
  404.     }

  405.     /** {@inheritDoc} */
  406.     public boolean equals(final Object other) {
  407.         try {
  408.             final TimeComponents otherTime = (TimeComponents) other;
  409.             return otherTime != null &&
  410.                    hour           == otherTime.hour   &&
  411.                    minute         == otherTime.minute &&
  412.                    second         == otherTime.second &&
  413.                    minutesFromUTC == otherTime.minutesFromUTC;
  414.         } catch (ClassCastException cce) {
  415.             return false;
  416.         }
  417.     }

  418.     /** {@inheritDoc} */
  419.     public int hashCode() {
  420.         final long bits = Double.doubleToLongBits(second);
  421.         return ((hour << 16) ^ ((minute - minutesFromUTC) << 8)) ^ (int) (bits ^ (bits >>> 32));
  422.     }

  423. }