AbsoluteDate.java

  1. /* Copyright 2002-2018 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (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.util.Date;
  20. import java.util.TimeZone;

  21. import org.hipparchus.util.FastMath;
  22. import org.hipparchus.util.MathArrays;
  23. import org.orekit.errors.OrekitException;
  24. import org.orekit.errors.OrekitIllegalArgumentException;
  25. import org.orekit.errors.OrekitMessages;
  26. import org.orekit.utils.Constants;


  27. /** This class represents a specific instant in time.

  28.  * <p>Instances of this class are considered to be absolute in the sense
  29.  * that each one represent the occurrence of some event and can be compared
  30.  * to other instances or located in <em>any</em> {@link TimeScale time scale}. In
  31.  * other words the different locations of an event with respect to two different
  32.  * time scales (say {@link TAIScale TAI} and {@link UTCScale UTC} for example) are
  33.  * simply different perspective related to a single object. Only one
  34.  * <code>AbsoluteDate</code> instance is needed, both representations being available
  35.  * from this single instance by specifying the time scales as parameter when calling
  36.  * the ad-hoc methods.</p>
  37.  *
  38.  * <p>Since an instance is not bound to a specific time-scale, all methods related
  39.  * to the location of the date within some time scale require to provide the time
  40.  * scale as an argument. It is therefore possible to define a date in one time scale
  41.  * and to use it in another one. An example of such use is to read a date from a file
  42.  * in UTC and write it in another file in TAI. This can be done as follows:</p>
  43.  * <pre>
  44.  *   DateTimeComponents utcComponents = readNextDate();
  45.  *   AbsoluteDate date = new AbsoluteDate(utcComponents, TimeScalesFactory.getUTC());
  46.  *   writeNextDate(date.getComponents(TimeScalesFactory.getTAI()));
  47.  * </pre>
  48.  *
  49.  * <p>Two complementary views are available:</p>
  50.  * <ul>
  51.  *   <li><p>location view (mainly for input/output or conversions)</p>
  52.  *   <p>locations represent the coordinate of one event with respect to a
  53.  *   {@link TimeScale time scale}. The related methods are {@link
  54.  *   #AbsoluteDate(DateComponents, TimeComponents, TimeScale)}, {@link
  55.  *   #AbsoluteDate(int, int, int, int, int, double, TimeScale)}, {@link
  56.  *   #AbsoluteDate(int, int, int, TimeScale)}, {@link #AbsoluteDate(Date,
  57.  *   TimeScale)}, {@link #createGPSDate(int, double)}, {@link
  58.  *   #parseCCSDSCalendarSegmentedTimeCode(byte, byte[])}, toString(){@link
  59.  *   #toDate(TimeScale)}, {@link #toString(TimeScale) toString(timeScale)},
  60.  *   {@link #toString()}, and {@link #timeScalesOffset}.</p>
  61.  *   </li>
  62.  *   <li><p>offset view (mainly for physical computation)</p>
  63.  *   <p>offsets represent either the flow of time between two events
  64.  *   (two instances of the class) or durations. They are counted in seconds,
  65.  *   are continuous and could be measured using only a virtually perfect stopwatch.
  66.  *   The related methods are {@link #AbsoluteDate(AbsoluteDate, double)},
  67.  *   {@link #parseCCSDSUnsegmentedTimeCode(byte, byte, byte[], AbsoluteDate)},
  68.  *   {@link #parseCCSDSDaySegmentedTimeCode(byte, byte[], DateComponents)},
  69.  *   {@link #durationFrom(AbsoluteDate)}, {@link #compareTo(AbsoluteDate)}, {@link #equals(Object)}
  70.  *   and {@link #hashCode()}.</p>
  71.  *   </li>
  72.  * </ul>
  73.  * <p>
  74.  * A few reference epochs which are commonly used in space systems have been defined. These
  75.  * epochs can be used as the basis for offset computation. The supported epochs are:
  76.  * {@link #JULIAN_EPOCH}, {@link #MODIFIED_JULIAN_EPOCH}, {@link #FIFTIES_EPOCH},
  77.  * {@link #CCSDS_EPOCH}, {@link #GALILEO_EPOCH}, {@link #GPS_EPOCH}, {@link #J2000_EPOCH},
  78.  * {@link #JAVA_EPOCH}. There are also two factory methods {@link #createJulianEpoch(double)}
  79.  * and {@link #createBesselianEpoch(double)} that can be used to compute other reference
  80.  * epochs like J1900.0 or B1950.0.
  81.  * In addition to these reference epochs, two other constants are defined for convenience:
  82.  * {@link #PAST_INFINITY} and {@link #FUTURE_INFINITY}, which can be used either as dummy
  83.  * dates when a date is not yet initialized, or for initialization of loops searching for
  84.  * a min or max date.
  85.  * </p>
  86.  * <p>
  87.  * Instances of the <code>AbsoluteDate</code> class are guaranteed to be immutable.
  88.  * </p>
  89.  * @author Luc Maisonobe
  90.  * @see TimeScale
  91.  * @see TimeStamped
  92.  * @see ChronologicalComparator
  93.  */
  94. public class AbsoluteDate
  95.     implements TimeStamped, TimeShiftable<AbsoluteDate>, Comparable<AbsoluteDate>, Serializable {

  96.     /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
  97.      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
  98.      * follow the astronomical conventions and consider a year 0 between
  99.      * years -1 and +1, hence this reference date lies in year -4712 and not
  100.      * in year -4713 as can be seen in other documents or programs that obey
  101.      * a different convention (for example the <code>convcal</code> utility).</p>
  102.      */
  103.     public static final AbsoluteDate JULIAN_EPOCH =
  104.         new AbsoluteDate(DateComponents.JULIAN_EPOCH, TimeComponents.H12, TimeScalesFactory.getTT());

  105.     /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time. */
  106.     public static final AbsoluteDate MODIFIED_JULIAN_EPOCH =
  107.         new AbsoluteDate(DateComponents.MODIFIED_JULIAN_EPOCH, TimeComponents.H00, TimeScalesFactory.getTT());

  108.     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time. */
  109.     public static final AbsoluteDate FIFTIES_EPOCH =
  110.         new AbsoluteDate(DateComponents.FIFTIES_EPOCH, TimeComponents.H00, TimeScalesFactory.getTT());

  111.     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
  112.      * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC). */
  113.     public static final AbsoluteDate CCSDS_EPOCH =
  114.         new AbsoluteDate(DateComponents.CCSDS_EPOCH, TimeComponents.H00, TimeScalesFactory.getTAI());

  115.     /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 UTC. */
  116.     public static final AbsoluteDate GALILEO_EPOCH =
  117.         new AbsoluteDate(DateComponents.GALILEO_EPOCH, new TimeComponents(0, 0, 32),
  118.                          TimeScalesFactory.getTAI());

  119.     /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time. */
  120.     public static final AbsoluteDate GPS_EPOCH =
  121.         new AbsoluteDate(DateComponents.GPS_EPOCH, TimeComponents.H00, TimeScalesFactory.getGPS());

  122.     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
  123.      * @see #createJulianEpoch(double)
  124.      * @see #createBesselianEpoch(double)
  125.      */
  126.     public static final AbsoluteDate J2000_EPOCH =
  127.         new AbsoluteDate(DateComponents.J2000_EPOCH, TimeComponents.H12, TimeScalesFactory.getTT());

  128.     /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
  129.      * <p>
  130.      * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
  131.      * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
  132.      * </p>
  133.      */
  134.     public static final AbsoluteDate JAVA_EPOCH =
  135.         new AbsoluteDate(DateComponents.JAVA_EPOCH, TimeScalesFactory.getTAI()).shiftedBy(8.000082);

  136.     /** Dummy date at infinity in the past direction. */
  137.     public static final AbsoluteDate PAST_INFINITY = JAVA_EPOCH.shiftedBy(Double.NEGATIVE_INFINITY);

  138.     /** Dummy date at infinity in the future direction. */
  139.     public static final AbsoluteDate FUTURE_INFINITY = JAVA_EPOCH.shiftedBy(Double.POSITIVE_INFINITY);

  140.     /** Serializable UID. */
  141.     private static final long serialVersionUID = 617061803741806846L;

  142.     /** Reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  143.      * <p>Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.</p> */
  144.     private final long epoch;

  145.     /** Offset from the reference epoch in seconds. */
  146.     private final double offset;

  147.     /** Create an instance with a default value ({@link #J2000_EPOCH}).
  148.      */
  149.     public AbsoluteDate() {
  150.         epoch  = J2000_EPOCH.epoch;
  151.         offset = J2000_EPOCH.offset;
  152.     }

  153.     /** Build an instance from a location (parsed from a string) in a {@link TimeScale time scale}.
  154.      * <p>
  155.      * The supported formats for location are mainly the ones defined in ISO-8601 standard,
  156.      * the exact subset is explained in {@link DateTimeComponents#parseDateTime(String)},
  157.      * {@link DateComponents#parseDate(String)} and {@link TimeComponents#parseTime(String)}.
  158.      * </p>
  159.      * <p>
  160.      * As CCSDS ASCII calendar segmented time code is a trimmed down version of ISO-8601,
  161.      * it is also supported by this constructor.
  162.      * </p>
  163.      * @param location location in the time scale, must be in a supported format
  164.      * @param timeScale time scale
  165.      * @exception IllegalArgumentException if location string is not in a supported format
  166.      */
  167.     public AbsoluteDate(final String location, final TimeScale timeScale) {
  168.         this(DateTimeComponents.parseDateTime(location), timeScale);
  169.     }

  170.     /** Build an instance from a location in a {@link TimeScale time scale}.
  171.      * @param location location in the time scale
  172.      * @param timeScale time scale
  173.      */
  174.     public AbsoluteDate(final DateTimeComponents location, final TimeScale timeScale) {
  175.         this(location.getDate(), location.getTime(), timeScale);
  176.     }

  177.     /** Build an instance from a location in a {@link TimeScale time scale}.
  178.      * @param date date location in the time scale
  179.      * @param time time location in the time scale
  180.      * @param timeScale time scale
  181.      */
  182.     public AbsoluteDate(final DateComponents date, final TimeComponents time,
  183.                         final TimeScale timeScale) {

  184.         final double seconds  = time.getSecond();
  185.         final double tsOffset = timeScale.offsetToTAI(date, time);

  186.         // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  187.         // the following statements must NOT be simplified, they rely on floating point
  188.         // arithmetic properties (rounding and representable numbers)
  189.         // at the end, the EXACT result of addition seconds + tsOffset
  190.         // is sum + residual, where sum is the closest representable number to the exact
  191.         // result and residual is the missing part that does not fit in the first number
  192.         final double sum      = seconds + tsOffset;
  193.         final double sPrime   = sum - tsOffset;
  194.         final double tPrime   = sum - sPrime;
  195.         final double deltaS   = seconds  - sPrime;
  196.         final double deltaT   = tsOffset - tPrime;
  197.         final double residual = deltaS   + deltaT;
  198.         final long   dl       = (long) FastMath.floor(sum);

  199.         offset = (sum - dl) + residual;
  200.         epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
  201.                         time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;

  202.     }

  203.     /** Build an instance from a location in a {@link TimeScale time scale}.
  204.      * @param year year number (may be 0 or negative for BC years)
  205.      * @param month month number from 1 to 12
  206.      * @param day day number from 1 to 31
  207.      * @param hour hour number from 0 to 23
  208.      * @param minute minute number from 0 to 59
  209.      * @param second second number from 0.0 to 60.0 (excluded)
  210.      * @param timeScale time scale
  211.      * @exception IllegalArgumentException if inconsistent arguments
  212.      * are given (parameters out of range)
  213.      */
  214.     public AbsoluteDate(final int year, final int month, final int day,
  215.                         final int hour, final int minute, final double second,
  216.                         final TimeScale timeScale) throws IllegalArgumentException {
  217.         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  218.     }

  219.     /** Build an instance from a location in a {@link TimeScale time scale}.
  220.      * @param year year number (may be 0 or negative for BC years)
  221.      * @param month month enumerate
  222.      * @param day day number from 1 to 31
  223.      * @param hour hour number from 0 to 23
  224.      * @param minute minute number from 0 to 59
  225.      * @param second second number from 0.0 to 60.0 (excluded)
  226.      * @param timeScale time scale
  227.      * @exception IllegalArgumentException if inconsistent arguments
  228.      * are given (parameters out of range)
  229.      */
  230.     public AbsoluteDate(final int year, final Month month, final int day,
  231.                         final int hour, final int minute, final double second,
  232.                         final TimeScale timeScale) throws IllegalArgumentException {
  233.         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  234.     }

  235.     /** Build an instance from a location in a {@link TimeScale time scale}.
  236.      * <p>The hour is set to 00:00:00.000.</p>
  237.      * @param date date location in the time scale
  238.      * @param timeScale time scale
  239.      * @exception IllegalArgumentException if inconsistent arguments
  240.      * are given (parameters out of range)
  241.      */
  242.     public AbsoluteDate(final DateComponents date, final TimeScale timeScale)
  243.         throws IllegalArgumentException {
  244.         this(date, TimeComponents.H00, timeScale);
  245.     }

  246.     /** Build an instance from a location in a {@link TimeScale time scale}.
  247.      * <p>The hour is set to 00:00:00.000.</p>
  248.      * @param year year number (may be 0 or negative for BC years)
  249.      * @param month month number from 1 to 12
  250.      * @param day day number from 1 to 31
  251.      * @param timeScale time scale
  252.      * @exception IllegalArgumentException if inconsistent arguments
  253.      * are given (parameters out of range)
  254.      */
  255.     public AbsoluteDate(final int year, final int month, final int day,
  256.                         final TimeScale timeScale) throws IllegalArgumentException {
  257.         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  258.     }

  259.     /** Build an instance from a location in a {@link TimeScale time scale}.
  260.      * <p>The hour is set to 00:00:00.000.</p>
  261.      * @param year year number (may be 0 or negative for BC years)
  262.      * @param month month enumerate
  263.      * @param day day number from 1 to 31
  264.      * @param timeScale time scale
  265.      * @exception IllegalArgumentException if inconsistent arguments
  266.      * are given (parameters out of range)
  267.      */
  268.     public AbsoluteDate(final int year, final Month month, final int day,
  269.                         final TimeScale timeScale) throws IllegalArgumentException {
  270.         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  271.     }

  272.     /** Build an instance from a location in a {@link TimeScale time scale}.
  273.      * @param location location in the time scale
  274.      * @param timeScale time scale
  275.      */
  276.     public AbsoluteDate(final Date location, final TimeScale timeScale) {
  277.         this(new DateComponents(DateComponents.JAVA_EPOCH,
  278.                                 (int) (location.getTime() / 86400000l)),
  279.                                 new TimeComponents(0.001 * (location.getTime() % 86400000l)),
  280.              timeScale);
  281.     }

  282.     /** Build an instance from an elapsed duration since to another instant.
  283.      * <p>It is important to note that the elapsed duration is <em>not</em>
  284.      * the difference between two readings on a time scale. As an example,
  285.      * the duration between the two instants leading to the readings
  286.      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
  287.      * time scale is <em>not</em> 1 second, but a stop watch would have measured
  288.      * an elapsed duration of 2 seconds between these two instances because a leap
  289.      * second was introduced at the end of 2005 in this time scale.</p>
  290.      * <p>This constructor is the reverse of the {@link #durationFrom(AbsoluteDate)}
  291.      * method.</p>
  292.      * @param since start instant of the measured duration
  293.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  294.      * instant, as measured in a regular time scale
  295.      * @see #durationFrom(AbsoluteDate)
  296.      */
  297.     public AbsoluteDate(final AbsoluteDate since, final double elapsedDuration) {

  298.         final double sum = since.offset + elapsedDuration;
  299.         if (Double.isInfinite(sum)) {
  300.             offset = sum;
  301.             epoch  = (sum < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  302.         } else {
  303.             // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  304.             // the following statements must NOT be simplified, they rely on floating point
  305.             // arithmetic properties (rounding and representable numbers)
  306.             // at the end, the EXACT result of addition since.offset + elapsedDuration
  307.             // is sum + residual, where sum is the closest representable number to the exact
  308.             // result and residual is the missing part that does not fit in the first number
  309.             final double oPrime   = sum - elapsedDuration;
  310.             final double dPrime   = sum - oPrime;
  311.             final double deltaO   = since.offset - oPrime;
  312.             final double deltaD   = elapsedDuration - dPrime;
  313.             final double residual = deltaO + deltaD;
  314.             final long   dl       = (long) FastMath.floor(sum);
  315.             offset = (sum - dl) + residual;
  316.             epoch  = since.epoch  + dl;
  317.         }
  318.     }

  319.     /** Build an instance from an apparent clock offset with respect to another
  320.      * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
  321.      * <p>It is important to note that the apparent clock offset <em>is</em> the
  322.      * difference between two readings on a time scale and <em>not</em> an elapsed
  323.      * duration. As an example, the apparent clock offset between the two instants
  324.      * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
  325.      * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
  326.      * seconds because a leap second has been introduced at the end of 2005 in this
  327.      * time scale.</p>
  328.      * <p>This constructor is the reverse of the {@link #offsetFrom(AbsoluteDate,
  329.      * TimeScale)} method.</p>
  330.      * @param reference reference instant
  331.      * @param apparentOffset apparent clock offset from the reference instant
  332.      * (difference between two readings in the specified time scale)
  333.      * @param timeScale time scale with respect to which the offset is defined
  334.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  335.      */
  336.     public AbsoluteDate(final AbsoluteDate reference, final double apparentOffset,
  337.                         final TimeScale timeScale) {
  338.         this(new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
  339.              timeScale);
  340.     }

  341.     /** Build a date from its internal components.
  342.      * <p>
  343.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  344.      * </p>
  345.      * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  346.      * (beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT)
  347.      * @param offset offset from the reference epoch in seconds (must be
  348.      * between 0.0 included and 1.0 excluded)
  349.      * @since 9.0
  350.      */
  351.     AbsoluteDate(final long epoch, final double offset) {
  352.         this.epoch  = epoch;
  353.         this.offset = offset;
  354.     }

  355.     /** Get the reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  356.      * <p>
  357.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  358.      * </p>
  359.      * <p>
  360.      * Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.
  361.      * </p>
  362.      * @return reference epoch in seconds from 2000-01-01T12:00:00 TAI
  363.      * @since 9.0
  364.      */
  365.     long getEpoch() {
  366.         return epoch;
  367.     }

  368.     /** Get the offset from the reference epoch in seconds.
  369.      * <p>
  370.      * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
  371.      * </p>
  372.      * @return offset from the reference epoch in seconds
  373.      * @since 9.0
  374.      */
  375.     double getOffset() {
  376.         return offset;
  377.     }

  378.     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
  379.      * <p>
  380.      * CCSDS Unsegmented Time Code is defined in the blue book:
  381.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  382.      * </p>
  383.      * <p>
  384.      * If the date to be parsed is formatted using version 3 of the standard
  385.      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
  386.      * field introduced in version 4 of the standard is not used, then the
  387.      * {@code preambleField2} parameter can be set to 0.
  388.      * </p>
  389.      * @param preambleField1 first byte of the field specifying the format, often
  390.      * not transmitted in data interfaces, as it is constant for a given data interface
  391.      * @param preambleField2 second byte of the field specifying the format
  392.      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
  393.      * interfaces, as it is constant for a given data interface (value ignored if presence
  394.      * not signaled in {@code preambleField1})
  395.      * @param timeField byte array containing the time code
  396.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  397.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  398.      * may be null in this case)
  399.      * @return an instance corresponding to the specified date
  400.      * @throws OrekitException if preamble is inconsistent with Unsegmented Time Code,
  401.      * or if it is inconsistent with time field, or if agency epoch is needed but not provided
  402.      */
  403.     public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(final byte preambleField1,
  404.                                                              final byte preambleField2,
  405.                                                              final byte[] timeField,
  406.                                                              final AbsoluteDate agencyDefinedEpoch)
  407.         throws OrekitException {

  408.         // time code identification and reference epoch
  409.         final AbsoluteDate epoch;
  410.         switch (preambleField1 & 0x70) {
  411.             case 0x10:
  412.                 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  413.                 epoch = CCSDS_EPOCH;
  414.                 break;
  415.             case 0x20:
  416.                 // the reference epoch is agency defined
  417.                 if (agencyDefinedEpoch == null) {
  418.                     throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  419.                 }
  420.                 epoch = agencyDefinedEpoch;
  421.                 break;
  422.             default :
  423.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  424.                                           formatByte(preambleField1));
  425.         }

  426.         // time field lengths
  427.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  428.         int fineTimeLength   = preambleField1 & 0x03;

  429.         if ((preambleField1 & 0x80) != 0x0) {
  430.             // there is an additional octet in preamble field
  431.             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
  432.             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
  433.         }

  434.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  435.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  436.                                       timeField.length, coarseTimeLength + fineTimeLength);
  437.         }

  438.         double seconds = 0;
  439.         for (int i = 0; i < coarseTimeLength; ++i) {
  440.             seconds = seconds * 256 + toUnsigned(timeField[i]);
  441.         }
  442.         double subseconds = 0;
  443.         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
  444.             subseconds = (subseconds + toUnsigned(timeField[i])) / 256;
  445.         }

  446.         return new AbsoluteDate(epoch, seconds).shiftedBy(subseconds);

  447.     }

  448.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  449.      * <p>
  450.      * CCSDS Day Segmented Time Code is defined in the blue book:
  451.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  452.      * </p>
  453.      * @param preambleField field specifying the format, often not transmitted in
  454.      * data interfaces, as it is constant for a given data interface
  455.      * @param timeField byte array containing the time code
  456.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  457.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  458.      * may be null in this case)
  459.      * @return an instance corresponding to the specified date
  460.      * @throws OrekitException if preamble is inconsistent with Day Segmented Time Code,
  461.      * or if it is inconsistent with time field, or if agency epoch is needed but not provided,
  462.      * or it UTC time scale cannot be retrieved
  463.      */
  464.     public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(final byte preambleField, final byte[] timeField,
  465.                                                               final DateComponents agencyDefinedEpoch)
  466.         throws OrekitException {

  467.         // time code identification
  468.         if ((preambleField & 0xF0) != 0x40) {
  469.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  470.                                       formatByte(preambleField));
  471.         }

  472.         // reference epoch
  473.         final DateComponents epoch;
  474.         if ((preambleField & 0x08) == 0x00) {
  475.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  476.             epoch = DateComponents.CCSDS_EPOCH;
  477.         } else {
  478.             // the reference epoch is agency defined
  479.             if (agencyDefinedEpoch == null) {
  480.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  481.             }
  482.             epoch = agencyDefinedEpoch;
  483.         }

  484.         // time field lengths
  485.         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
  486.         final int subMillisecondLength = (preambleField & 0x03) << 1;
  487.         if (subMillisecondLength == 6) {
  488.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  489.                                       formatByte(preambleField));
  490.         }
  491.         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
  492.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  493.                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
  494.         }


  495.         int i   = 0;
  496.         int day = 0;
  497.         while (i < daySegmentLength) {
  498.             day = day * 256 + toUnsigned(timeField[i++]);
  499.         }

  500.         long milliInDay = 0l;
  501.         while (i < daySegmentLength + 4) {
  502.             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
  503.         }
  504.         final int milli   = (int) (milliInDay % 1000l);
  505.         final int seconds = (int) ((milliInDay - milli) / 1000l);

  506.         double subMilli = 0;
  507.         double divisor  = 1;
  508.         while (i < timeField.length) {
  509.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  510.             divisor *= 1000;
  511.         }

  512.         final DateComponents date = new DateComponents(epoch, day);
  513.         final TimeComponents time = new TimeComponents(seconds);
  514.         return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(milli * 1.0e-3 + subMilli / divisor);

  515.     }

  516.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  517.      * <p>
  518.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  519.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  520.      * </p>
  521.      * @param preambleField field specifying the format, often not transmitted in
  522.      * data interfaces, as it is constant for a given data interface
  523.      * @param timeField byte array containing the time code
  524.      * @return an instance corresponding to the specified date
  525.      * @throws OrekitException if preamble is inconsistent with Calendar Segmented Time Code,
  526.      * or if it is inconsistent with time field, or it UTC time scale cannot be retrieved
  527.      */
  528.     public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField)
  529.         throws OrekitException {

  530.         // time code identification
  531.         if ((preambleField & 0xF0) != 0x50) {
  532.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  533.                                       formatByte(preambleField));
  534.         }

  535.         // time field length
  536.         final int length = 7 + (preambleField & 0x07);
  537.         if (length == 14) {
  538.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  539.                                       formatByte(preambleField));
  540.         }
  541.         if (timeField.length != length) {
  542.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  543.                                       timeField.length, length);
  544.         }

  545.         // date part in the first four bytes
  546.         final DateComponents date;
  547.         if ((preambleField & 0x08) == 0x00) {
  548.             // month of year and day of month variation
  549.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  550.                                       toUnsigned(timeField[2]),
  551.                                       toUnsigned(timeField[3]));
  552.         } else {
  553.             // day of year variation
  554.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  555.                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
  556.         }

  557.         // time part from bytes 5 to last (between 7 and 13 depending on precision)
  558.         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
  559.                                                        toUnsigned(timeField[5]),
  560.                                                        toUnsigned(timeField[6]));
  561.         double subSecond = 0;
  562.         double divisor   = 1;
  563.         for (int i = 7; i < length; ++i) {
  564.             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
  565.             divisor *= 100;
  566.         }

  567.         return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(subSecond / divisor);

  568.     }

  569.     /** Decode a signed byte as an unsigned int value.
  570.      * @param b byte to decode
  571.      * @return an unsigned int value
  572.      */
  573.     private static int toUnsigned(final byte b) {
  574.         final int i = (int) b;
  575.         return (i < 0) ? 256 + i : i;
  576.     }

  577.     /** Format a byte as an hex string for error messages.
  578.      * @param data byte to format
  579.      * @return a formatted string
  580.      */
  581.     private static String formatByte(final byte data) {
  582.         return "0x" + Integer.toHexString(data).toUpperCase();
  583.     }

  584.     /** Build an instance corresponding to a Julian Day date.
  585.      * @param jd Julian day
  586.      * @param secondsSinceNoon seconds in the Julian day
  587.      * (BEWARE, Julian days start at noon, so 0.0 is noon)
  588.      * @param timeScale time scale in which the seconds in day are defined
  589.      * @return a new instant
  590.      */
  591.     public static AbsoluteDate createJDDate(final int jd, final double secondsSinceNoon,
  592.                                              final TimeScale timeScale) {
  593.         return new AbsoluteDate(new DateComponents(DateComponents.JULIAN_EPOCH, jd),
  594.                                 TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
  595.     }

  596.     /** Build an instance corresponding to a Modified Julian Day date.
  597.      * @param mjd modified Julian day
  598.      * @param secondsInDay seconds in the day
  599.      * @param timeScale time scale in which the seconds in day are defined
  600.      * @return a new instant
  601.      * @exception OrekitIllegalArgumentException if seconds number is out of range
  602.      */
  603.     public static AbsoluteDate createMJDDate(final int mjd, final double secondsInDay,
  604.                                              final TimeScale timeScale)
  605.         throws OrekitIllegalArgumentException {
  606.         final DateComponents dc = new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd);
  607.         final TimeComponents tc;
  608.         if (secondsInDay >= Constants.JULIAN_DAY) {
  609.             // check we are really allowed to use this number of seconds
  610.             final int    secondsA = 86399; // 23:59:59, i.e. 59s in the last minute of the day
  611.             final double secondsB = secondsInDay - secondsA;
  612.             final TimeComponents safeTC = new TimeComponents(secondsA, 0.0);
  613.             final AbsoluteDate safeDate = new AbsoluteDate(dc, safeTC, timeScale);
  614.             if (timeScale.minuteDuration(safeDate) > 59 + secondsB) {
  615.                 // we are within the last minute of the day, the number of seconds is OK
  616.                 return safeDate.shiftedBy(secondsB);
  617.             } else {
  618.                 // let TimeComponents trigger an OrekitIllegalArgumentException
  619.                 // for the wrong number of seconds
  620.                 tc = new TimeComponents(secondsA, secondsB);
  621.             }
  622.         } else {
  623.             tc = new TimeComponents(secondsInDay);
  624.         }

  625.         // create the date
  626.         return new AbsoluteDate(dc, tc, timeScale);

  627.     }


  628.     /** Build an instance corresponding to a GPS date.
  629.      * <p>GPS dates are provided as a week number starting at
  630.      * {@link #GPS_EPOCH GPS epoch} and as a number of milliseconds
  631.      * since week start.</p>
  632.      * @param weekNumber week number since {@link #GPS_EPOCH GPS epoch}
  633.      * @param milliInWeek number of milliseconds since week start
  634.      * @return a new instant
  635.      */
  636.     public static AbsoluteDate createGPSDate(final int weekNumber,
  637.                                              final double milliInWeek) {
  638.         final int day = (int) FastMath.floor(milliInWeek / (1000.0 * Constants.JULIAN_DAY));
  639.         final double secondsInDay = milliInWeek / 1000.0 - day * Constants.JULIAN_DAY;
  640.         return new AbsoluteDate(new DateComponents(DateComponents.GPS_EPOCH, weekNumber * 7 + day),
  641.                                 new TimeComponents(secondsInDay),
  642.                                 TimeScalesFactory.getGPS());
  643.     }

  644.     /** Build an instance corresponding to a Julian Epoch (JE).
  645.      * <p>According to Lieske paper: <a
  646.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
  647.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  648.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
  649.      * <pre>
  650.      * JE = 2000.0 + (JED - 2451545.0) / 365.25
  651.      * </pre>
  652.      * <p>
  653.      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Julian Epoch.
  654.      * </p>
  655.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
  656.      * @return a new instant
  657.      * @see #J2000_EPOCH
  658.      * @see #createBesselianEpoch(double)
  659.      */
  660.     public static AbsoluteDate createJulianEpoch(final double julianEpoch) {
  661.         return new AbsoluteDate(J2000_EPOCH,
  662.                                 Constants.JULIAN_YEAR * (julianEpoch - 2000.0));
  663.     }

  664.     /** Build an instance corresponding to a Besselian Epoch (BE).
  665.      * <p>According to Lieske paper: <a
  666.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
  667.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  668.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
  669.      * <pre>
  670.      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
  671.      * </pre>
  672.      * <p>
  673.      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Besselian Epoch.
  674.      * </p>
  675.      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
  676.      * @return a new instant
  677.      * @see #createJulianEpoch(double)
  678.      */
  679.     public static AbsoluteDate createBesselianEpoch(final double besselianEpoch) {
  680.         return new AbsoluteDate(J2000_EPOCH,
  681.                                 MathArrays.linearCombination(Constants.BESSELIAN_YEAR, besselianEpoch - 1900,
  682.                                                              Constants.JULIAN_DAY, -36525,
  683.                                                              Constants.JULIAN_DAY, 0.31352));
  684.     }

  685.     /** Get a time-shifted date.
  686.      * <p>
  687.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  688.      * </p>
  689.      * @param dt time shift in seconds
  690.      * @return a new date, shifted with respect to instance (which is immutable)
  691.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  692.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  693.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  694.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  695.      */
  696.     public AbsoluteDate shiftedBy(final double dt) {
  697.         return new AbsoluteDate(this, dt);
  698.     }

  699.     /** Compute the physically elapsed duration between two instants.
  700.      * <p>The returned duration is the number of seconds physically
  701.      * elapsed between the two instants, measured in a regular time
  702.      * scale with respect to surface of the Earth (i.e either the {@link
  703.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  704.      * GPSScale GPS scale}). It is the only method that gives a
  705.      * duration with a physical meaning.</p>
  706.      * <p>This method gives the same result (with less computation)
  707.      * as calling {@link #offsetFrom(AbsoluteDate, TimeScale)}
  708.      * with a second argument set to one of the regular scales cited
  709.      * above.</p>
  710.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  711.      * double)} constructor.</p>
  712.      * @param instant instant to subtract from the instance
  713.      * @return offset in seconds between the two instants (positive
  714.      * if the instance is posterior to the argument)
  715.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  716.      * @see #AbsoluteDate(AbsoluteDate, double)
  717.      */
  718.     public double durationFrom(final AbsoluteDate instant) {
  719.         return (epoch - instant.epoch) + (offset - instant.offset);
  720.     }

  721.     /** Compute the apparent clock offset between two instant <em>in the
  722.      * perspective of a specific {@link TimeScale time scale}</em>.
  723.      * <p>The offset is the number of seconds counted in the given
  724.      * time scale between the locations of the two instants, with
  725.      * all time scale irregularities removed (i.e. considering all
  726.      * days are exactly 86400 seconds long). This method will give
  727.      * a result that may not have a physical meaning if the time scale
  728.      * is irregular. For example since a leap second was introduced at
  729.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  730.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  731.      * of the corresponding time interval as returned by the {@link
  732.      * #durationFrom(AbsoluteDate)} method is 2 seconds.</p>
  733.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  734.      * double, TimeScale)} constructor.</p>
  735.      * @param instant instant to subtract from the instance
  736.      * @param timeScale time scale with respect to which the offset should
  737.      * be computed
  738.      * @return apparent clock offset in seconds between the two instants
  739.      * (positive if the instance is posterior to the argument)
  740.      * @see #durationFrom(AbsoluteDate)
  741.      * @see #AbsoluteDate(AbsoluteDate, double, TimeScale)
  742.      */
  743.     public double offsetFrom(final AbsoluteDate instant, final TimeScale timeScale) {
  744.         final long   elapsedDurationA = epoch - instant.epoch;
  745.         final double elapsedDurationB = (offset         + timeScale.offsetFromTAI(this)) -
  746.                                         (instant.offset + timeScale.offsetFromTAI(instant));
  747.         return  elapsedDurationA + elapsedDurationB;
  748.     }

  749.     /** Compute the offset between two time scales at the current instant.
  750.      * <p>The offset is defined as <i>l₁-l₂</i>
  751.      * where <i>l₁</i> is the location of the instant in
  752.      * the <code>scale1</code> time scale and <i>l₂</i> is the
  753.      * location of the instant in the <code>scale2</code> time scale.</p>
  754.      * @param scale1 first time scale
  755.      * @param scale2 second time scale
  756.      * @return offset in seconds between the two time scales at the
  757.      * current instant
  758.      */
  759.     public double timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  760.         return scale1.offsetFromTAI(this) - scale2.offsetFromTAI(this);
  761.     }

  762.     /** Convert the instance to a Java {@link java.util.Date Date}.
  763.      * <p>Conversion to the Date class induces a loss of precision because
  764.      * the Date class does not provide sub-millisecond information. Java Dates
  765.      * are considered to be locations in some times scales.</p>
  766.      * @param timeScale time scale to use
  767.      * @return a {@link java.util.Date Date} instance representing the location
  768.      * of the instant in the time scale
  769.      */
  770.     public Date toDate(final TimeScale timeScale) {
  771.         final double time = epoch + (offset + timeScale.offsetFromTAI(this));
  772.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  773.     }

  774.     /** Split the instance into date/time components.
  775.      * @param timeScale time scale to use
  776.      * @return date/time components
  777.      */
  778.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  779.         if (Double.isInfinite(offset)) {
  780.             // special handling for past and future infinity
  781.             if (offset < 0) {
  782.                 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
  783.             } else {
  784.                 return new DateTimeComponents(DateComponents.MAX_EPOCH,
  785.                                               new TimeComponents(23, 59, 59.999));
  786.             }
  787.         }

  788.         // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
  789.         // using Møller-Knuth TwoSum algorithm without branching
  790.         // the following statements must NOT be simplified, they rely on floating point
  791.         // arithmetic properties (rounding and representable numbers)
  792.         // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
  793.         // is sum + residual, where sum is the closest representable number to the exact
  794.         // result and residual is the missing part that does not fit in the first number
  795.         final double taiOffset = timeScale.offsetFromTAI(this);
  796.         final double sum       = offset + taiOffset;
  797.         final double oPrime    = sum - taiOffset;
  798.         final double dPrime    = sum - oPrime;
  799.         final double deltaO    = offset - oPrime;
  800.         final double deltaD    = taiOffset - dPrime;
  801.         final double residual  = deltaO + deltaD;

  802.         // split date and time
  803.         final long   carry = (long) FastMath.floor(sum);
  804.         double offset2000B = (sum - carry) + residual;
  805.         long   offset2000A = epoch + carry + 43200l;
  806.         if (offset2000B < 0) {
  807.             offset2000A -= 1;
  808.             offset2000B += 1;
  809.         }
  810.         long time = offset2000A % 86400l;
  811.         if (time < 0l) {
  812.             time += 86400l;
  813.         }
  814.         final int date = (int) ((offset2000A - time) / 86400l);

  815.         // extract calendar elements
  816.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  817.         TimeComponents timeComponents = new TimeComponents((int) time, offset2000B);

  818.         if (timeScale.insideLeap(this)) {
  819.             // fix the seconds number to take the leap into account
  820.             timeComponents = new TimeComponents(timeComponents.getHour(), timeComponents.getMinute(),
  821.                                                 timeComponents.getSecond() + timeScale.getLeap(this));
  822.         }

  823.         // build the components
  824.         return new DateTimeComponents(dateComponents, timeComponents);

  825.     }

  826.     /** Split the instance into date/time components for a local time.
  827.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  828.      * negative Westward UTC)
  829.      * @return date/time components
  830.      * @exception OrekitException if UTC time scale cannot be retrieved
  831.      * @since 7.2
  832.      */
  833.     public DateTimeComponents getComponents(final int minutesFromUTC)
  834.         throws OrekitException {

  835.         final DateTimeComponents utcComponents = getComponents(TimeScalesFactory.getUTC());

  836.         // shift the date according to UTC offset, but WITHOUT touching the seconds,
  837.         // as they may exceed 60.0 during a leap seconds introduction,
  838.         // and we want to preserve these special cases
  839.         final double seconds = utcComponents.getTime().getSecond();

  840.         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
  841.         final int hourShift;
  842.         if (minute < 0) {
  843.             hourShift = (minute - 59) / 60;
  844.         } else if (minute > 59) {
  845.             hourShift = minute / 60;
  846.         } else {
  847.             hourShift = 0;
  848.         }
  849.         minute -= 60 * hourShift;

  850.         int hour = utcComponents.getTime().getHour() + hourShift;
  851.         final int dayShift;
  852.         if (hour < 0) {
  853.             dayShift = (hour - 23) / 24;
  854.         } else if (hour > 23) {
  855.             dayShift = hour / 24;
  856.         } else {
  857.             dayShift = 0;
  858.         }
  859.         hour -= 24 * dayShift;

  860.         return new DateTimeComponents(new DateComponents(utcComponents.getDate(), dayShift),
  861.                                       new TimeComponents(hour, minute, seconds, minutesFromUTC));

  862.     }

  863.     /** Split the instance into date/time components for a time zone.
  864.      * @param timeZone time zone
  865.      * @return date/time components
  866.      * @exception OrekitException if UTC time scale cannot be retrieved
  867.      * @since 7.2
  868.      */
  869.     public DateTimeComponents getComponents(final TimeZone timeZone)
  870.         throws OrekitException {
  871.         final long milliseconds = FastMath.round(1000 * offsetFrom(JAVA_EPOCH, TimeScalesFactory.getUTC()));
  872.         return getComponents(timeZone.getOffset(milliseconds) / 60000);
  873.     }

  874.     /** Compare the instance with another date.
  875.      * @param date other date to compare the instance to
  876.      * @return a negative integer, zero, or a positive integer as this date
  877.      * is before, simultaneous, or after the specified date.
  878.      */
  879.     public int compareTo(final AbsoluteDate date) {
  880.         return Double.compare(durationFrom(date),  0);
  881.     }

  882.     /** {@inheritDoc} */
  883.     public AbsoluteDate getDate() {
  884.         return this;
  885.     }

  886.     /** Check if the instance represent the same time as another instance.
  887.      * @param date other date
  888.      * @return true if the instance and the other date refer to the same instant
  889.      */
  890.     public boolean equals(final Object date) {

  891.         if (date == this) {
  892.             // first fast check
  893.             return true;
  894.         }

  895.         if ((date != null) && (date instanceof AbsoluteDate)) {
  896.             return durationFrom((AbsoluteDate) date) == 0;
  897.         }

  898.         return false;

  899.     }

  900.     /** Get a hashcode for this date.
  901.      * @return hashcode
  902.      */
  903.     public int hashCode() {
  904.         final long l = Double.doubleToLongBits(durationFrom(J2000_EPOCH));
  905.         return (int) (l ^ (l >>> 32));
  906.     }

  907.     /** Get a String representation of the instant location in UTC time scale.
  908.      * @return a string representation of the instance,
  909.      * in ISO-8601 format with milliseconds accuracy
  910.      */
  911.     public String toString() {
  912.         try {
  913.             return toString(TimeScalesFactory.getUTC());
  914.         } catch (OrekitException oe) {
  915.             throw new RuntimeException(oe);
  916.         }
  917.     }

  918.     /** Get a String representation of the instant location.
  919.      * @param timeScale time scale to use
  920.      * @return a string representation of the instance,
  921.      * in ISO-8601 format with milliseconds accuracy
  922.      */
  923.     public String toString(final TimeScale timeScale) {
  924.         return getComponents(timeScale).toString(timeScale.minuteDuration(this));
  925.     }

  926.     /** Get a String representation of the instant location for a local time.
  927.      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
  928.      * negative Westward UTC).
  929.      * @return string representation of the instance,
  930.      * in ISO-8601 format with milliseconds accuracy
  931.      * @exception OrekitException if UTC time scale cannot be retrieved
  932.      * @since 7.2
  933.      */
  934.     public String toString(final int minutesFromUTC)
  935.         throws OrekitException {
  936.         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
  937.         return getComponents(minutesFromUTC).toString(minuteDuration);
  938.     }

  939.     /** Get a String representation of the instant location for a time zone.
  940.      * @param timeZone time zone
  941.      * @return string representation of the instance,
  942.      * in ISO-8601 format with milliseconds accuracy
  943.      * @exception OrekitException if UTC time scale cannot be retrieved
  944.      * @since 7.2
  945.      */
  946.     public String toString(final TimeZone timeZone)
  947.         throws OrekitException {
  948.         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
  949.         return getComponents(timeZone).toString(minuteDuration);
  950.     }

  951. }