1   /* Copyright 2002-2016 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  
19  import java.io.Serializable;
20  import java.util.Date;
21  import java.util.TimeZone;
22  
23  import org.hipparchus.util.FastMath;
24  import org.hipparchus.util.MathArrays;
25  import org.orekit.errors.OrekitException;
26  import org.orekit.errors.OrekitMessages;
27  import org.orekit.utils.Constants;
28  
29  
30  /** This class represents a specific instant in time.
31  
32   * <p>Instances of this class are considered to be absolute in the sense
33   * that each one represent the occurrence of some event and can be compared
34   * to other instances or located in <em>any</em> {@link TimeScale time scale}. In
35   * other words the different locations of an event with respect to two different
36   * time scales (say {@link TAIScale TAI} and {@link UTCScale UTC} for example) are
37   * simply different perspective related to a single object. Only one
38   * <code>AbsoluteDate</code> instance is needed, both representations being available
39   * from this single instance by specifying the time scales as parameter when calling
40   * the ad-hoc methods.</p>
41   *
42   * <p>Since an instance is not bound to a specific time-scale, all methods related
43   * to the location of the date within some time scale require to provide the time
44   * scale as an argument. It is therefore possible to define a date in one time scale
45   * and to use it in another one. An example of such use is to read a date from a file
46   * in UTC and write it in another file in TAI. This can be done as follows:</p>
47   * <pre>
48   *   DateTimeComponents utcComponents = readNextDate();
49   *   AbsoluteDate date = new AbsoluteDate(utcComponents, TimeScalesFactory.getUTC());
50   *   writeNextDate(date.getComponents(TimeScalesFactory.getTAI()));
51   * </pre>
52   *
53   * <p>Two complementary views are available:</p>
54   * <ul>
55   *   <li><p>location view (mainly for input/output or conversions)</p>
56   *   <p>locations represent the coordinate of one event with respect to a
57   *   {@link TimeScale time scale}. The related methods are {@link
58   *   #AbsoluteDate(DateComponents, TimeComponents, TimeScale)}, {@link
59   *   #AbsoluteDate(int, int, int, int, int, double, TimeScale)}, {@link
60   *   #AbsoluteDate(int, int, int, TimeScale)}, {@link #AbsoluteDate(Date,
61   *   TimeScale)}, {@link #createGPSDate(int, double)}, {@link
62   *   #parseCCSDSCalendarSegmentedTimeCode(byte, byte[])}, toString(){@link
63   *   #toDate(TimeScale)}, {@link #toString(TimeScale) toString(timeScale)},
64   *   {@link #toString()}, and {@link #timeScalesOffset}.</p>
65   *   </li>
66   *   <li><p>offset view (mainly for physical computation)</p>
67   *   <p>offsets represent either the flow of time between two events
68   *   (two instances of the class) or durations. They are counted in seconds,
69   *   are continuous and could be measured using only a virtually perfect stopwatch.
70   *   The related methods are {@link #AbsoluteDate(AbsoluteDate, double)},
71   *   {@link #parseCCSDSUnsegmentedTimeCode(byte, byte, byte[], AbsoluteDate)},
72   *   {@link #parseCCSDSDaySegmentedTimeCode(byte, byte[], DateComponents)},
73   *   {@link #durationFrom(AbsoluteDate)}, {@link #compareTo(AbsoluteDate)}, {@link #equals(Object)}
74   *   and {@link #hashCode()}.</p>
75   *   </li>
76   * </ul>
77   * <p>
78   * A few reference epochs which are commonly used in space systems have been defined. These
79   * epochs can be used as the basis for offset computation. The supported epochs are:
80   * {@link #JULIAN_EPOCH}, {@link #MODIFIED_JULIAN_EPOCH}, {@link #FIFTIES_EPOCH},
81   * {@link #CCSDS_EPOCH}, {@link #GALILEO_EPOCH}, {@link #GPS_EPOCH}, {@link #J2000_EPOCH},
82   * {@link #JAVA_EPOCH}. There are also two factory methods {@link #createJulianEpoch(double)}
83   * and {@link #createBesselianEpoch(double)} that can be used to compute other reference
84   * epochs like J1900.0 or B1950.0.
85   * In addition to these reference epochs, two other constants are defined for convenience:
86   * {@link #PAST_INFINITY} and {@link #FUTURE_INFINITY}, which can be used either as dummy
87   * dates when a date is not yet initialized, or for initialization of loops searching for
88   * a min or max date.
89   * </p>
90   * <p>
91   * Instances of the <code>AbsoluteDate</code> class are guaranteed to be immutable.
92   * </p>
93   * @author Luc Maisonobe
94   * @see TimeScale
95   * @see TimeStamped
96   * @see ChronologicalComparator
97   */
98  public class AbsoluteDate
99      implements TimeStamped, TimeShiftable<AbsoluteDate>, Comparable<AbsoluteDate>, Serializable {
100 
101     /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
102      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
103      * follow the astronomical conventions and consider a year 0 between
104      * years -1 and +1, hence this reference date lies in year -4712 and not
105      * in year -4713 as can be seen in other documents or programs that obey
106      * a different convention (for example the <code>convcal</code> utility).</p>
107      */
108     public static final AbsoluteDate JULIAN_EPOCH =
109         new AbsoluteDate(DateComponents.JULIAN_EPOCH, TimeComponents.H12, TimeScalesFactory.getTT());
110 
111     /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time. */
112     public static final AbsoluteDate MODIFIED_JULIAN_EPOCH =
113         new AbsoluteDate(DateComponents.MODIFIED_JULIAN_EPOCH, TimeComponents.H00, TimeScalesFactory.getTT());
114 
115     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time. */
116     public static final AbsoluteDate FIFTIES_EPOCH =
117         new AbsoluteDate(DateComponents.FIFTIES_EPOCH, TimeComponents.H00, TimeScalesFactory.getTT());
118 
119     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
120      * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC). */
121     public static final AbsoluteDate CCSDS_EPOCH =
122         new AbsoluteDate(DateComponents.CCSDS_EPOCH, TimeComponents.H00, TimeScalesFactory.getTAI());
123 
124     /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 UTC. */
125     public static final AbsoluteDate GALILEO_EPOCH =
126         new AbsoluteDate(DateComponents.GALILEO_EPOCH, new TimeComponents(0, 0, 32),
127                          TimeScalesFactory.getTAI());
128 
129     /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time. */
130     public static final AbsoluteDate GPS_EPOCH =
131         new AbsoluteDate(DateComponents.GPS_EPOCH, TimeComponents.H00, TimeScalesFactory.getGPS());
132 
133     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
134      * @see #createJulianEpoch(double)
135      * @see #createBesselianEpoch(double)
136      */
137     public static final AbsoluteDate J2000_EPOCH =
138         new AbsoluteDate(DateComponents.J2000_EPOCH, TimeComponents.H12, TimeScalesFactory.getTT());
139 
140     /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
141      * <p>
142      * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
143      * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
144      * </p>
145      */
146     public static final AbsoluteDate JAVA_EPOCH =
147         new AbsoluteDate(DateComponents.JAVA_EPOCH, TimeScalesFactory.getTAI()).shiftedBy(8.000082);
148 
149     /** Dummy date at infinity in the past direction. */
150     public static final AbsoluteDate PAST_INFINITY = JAVA_EPOCH.shiftedBy(Double.NEGATIVE_INFINITY);
151 
152     /** Dummy date at infinity in the future direction. */
153     public static final AbsoluteDate FUTURE_INFINITY = JAVA_EPOCH.shiftedBy(Double.POSITIVE_INFINITY);
154 
155     /** Serializable UID. */
156     private static final long serialVersionUID = 617061803741806846L;
157 
158     /** Reference epoch in seconds from 2000-01-01T12:00:00 TAI.
159      * <p>Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.</p> */
160     private final long epoch;
161 
162     /** Offset from the reference epoch in seconds. */
163     private final double offset;
164 
165     /** Create an instance with a default value ({@link #J2000_EPOCH}).
166      */
167     public AbsoluteDate() {
168         epoch  = J2000_EPOCH.epoch;
169         offset = J2000_EPOCH.offset;
170     }
171 
172     /** Build an instance from a location (parsed from a string) in a {@link TimeScale time scale}.
173      * <p>
174      * The supported formats for location are mainly the ones defined in ISO-8601 standard,
175      * the exact subset is explained in {@link DateTimeComponents#parseDateTime(String)},
176      * {@link DateComponents#parseDate(String)} and {@link TimeComponents#parseTime(String)}.
177      * </p>
178      * <p>
179      * As CCSDS ASCII calendar segmented time code is a trimmed down version of ISO-8601,
180      * it is also supported by this constructor.
181      * </p>
182      * @param location location in the time scale, must be in a supported format
183      * @param timeScale time scale
184      * @exception IllegalArgumentException if location string is not in a supported format
185      */
186     public AbsoluteDate(final String location, final TimeScale timeScale) {
187         this(DateTimeComponents.parseDateTime(location), timeScale);
188     }
189 
190     /** Build an instance from a location in a {@link TimeScale time scale}.
191      * @param location location in the time scale
192      * @param timeScale time scale
193      */
194     public AbsoluteDate(final DateTimeComponents location, final TimeScale timeScale) {
195         this(location.getDate(), location.getTime(), timeScale);
196     }
197 
198     /** Build an instance from a location in a {@link TimeScale time scale}.
199      * @param date date location in the time scale
200      * @param time time location in the time scale
201      * @param timeScale time scale
202      */
203     public AbsoluteDate(final DateComponents date, final TimeComponents time,
204                         final TimeScale timeScale) {
205 
206         final double seconds  = time.getSecond();
207         final double tsOffset = timeScale.offsetToTAI(date, time);
208 
209         // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
210         // the following statements must NOT be simplified, they rely on floating point
211         // arithmetic properties (rounding and representable numbers)
212         // at the end, the EXACT result of addition seconds + tsOffset
213         // is sum + residual, where sum is the closest representable number to the exact
214         // result and residual is the missing part that does not fit in the first number
215         final double sum      = seconds + tsOffset;
216         final double sPrime   = sum - tsOffset;
217         final double tPrime   = sum - sPrime;
218         final double deltaS   = seconds  - sPrime;
219         final double deltaT   = tsOffset - tPrime;
220         final double residual = deltaS   + deltaT;
221         final long   dl       = (long) FastMath.floor(sum);
222 
223         offset = (sum - dl) + residual;
224         epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
225                         time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;
226 
227     }
228 
229     /** Build an instance from a location in a {@link TimeScale time scale}.
230      * @param year year number (may be 0 or negative for BC years)
231      * @param month month number from 1 to 12
232      * @param day day number from 1 to 31
233      * @param hour hour number from 0 to 23
234      * @param minute minute number from 0 to 59
235      * @param second second number from 0.0 to 60.0 (excluded)
236      * @param timeScale time scale
237      * @exception IllegalArgumentException if inconsistent arguments
238      * are given (parameters out of range)
239      */
240     public AbsoluteDate(final int year, final int month, final int day,
241                         final int hour, final int minute, final double second,
242                         final TimeScale timeScale) throws IllegalArgumentException {
243         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
244     }
245 
246     /** Build an instance from a location in a {@link TimeScale time scale}.
247      * @param year year number (may be 0 or negative for BC years)
248      * @param month month enumerate
249      * @param day day number from 1 to 31
250      * @param hour hour number from 0 to 23
251      * @param minute minute number from 0 to 59
252      * @param second second number from 0.0 to 60.0 (excluded)
253      * @param timeScale time scale
254      * @exception IllegalArgumentException if inconsistent arguments
255      * are given (parameters out of range)
256      */
257     public AbsoluteDate(final int year, final Month month, final int day,
258                         final int hour, final int minute, final double second,
259                         final TimeScale timeScale) throws IllegalArgumentException {
260         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
261     }
262 
263     /** Build an instance from a location in a {@link TimeScale time scale}.
264      * <p>The hour is set to 00:00:00.000.</p>
265      * @param date date location in the time scale
266      * @param timeScale time scale
267      * @exception IllegalArgumentException if inconsistent arguments
268      * are given (parameters out of range)
269      */
270     public AbsoluteDate(final DateComponents date, final TimeScale timeScale)
271         throws IllegalArgumentException {
272         this(date, TimeComponents.H00, timeScale);
273     }
274 
275     /** Build an instance from a location in a {@link TimeScale time scale}.
276      * <p>The hour is set to 00:00:00.000.</p>
277      * @param year year number (may be 0 or negative for BC years)
278      * @param month month number from 1 to 12
279      * @param day day number from 1 to 31
280      * @param timeScale time scale
281      * @exception IllegalArgumentException if inconsistent arguments
282      * are given (parameters out of range)
283      */
284     public AbsoluteDate(final int year, final int month, final int day,
285                         final TimeScale timeScale) throws IllegalArgumentException {
286         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
287     }
288 
289     /** Build an instance from a location in a {@link TimeScale time scale}.
290      * <p>The hour is set to 00:00:00.000.</p>
291      * @param year year number (may be 0 or negative for BC years)
292      * @param month month enumerate
293      * @param day day number from 1 to 31
294      * @param timeScale time scale
295      * @exception IllegalArgumentException if inconsistent arguments
296      * are given (parameters out of range)
297      */
298     public AbsoluteDate(final int year, final Month month, final int day,
299                         final TimeScale timeScale) throws IllegalArgumentException {
300         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
301     }
302 
303     /** Build an instance from a location in a {@link TimeScale time scale}.
304      * @param location location in the time scale
305      * @param timeScale time scale
306      */
307     public AbsoluteDate(final Date location, final TimeScale timeScale) {
308         this(new DateComponents(DateComponents.JAVA_EPOCH,
309                                 (int) (location.getTime() / 86400000l)),
310                                 new TimeComponents(0.001 * (location.getTime() % 86400000l)),
311              timeScale);
312     }
313 
314     /** Build an instance from an elapsed duration since to another instant.
315      * <p>It is important to note that the elapsed duration is <em>not</em>
316      * the difference between two readings on a time scale. As an example,
317      * the duration between the two instants leading to the readings
318      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
319      * time scale is <em>not</em> 1 second, but a stop watch would have measured
320      * an elapsed duration of 2 seconds between these two instances because a leap
321      * second was introduced at the end of 2005 in this time scale.</p>
322      * <p>This constructor is the reverse of the {@link #durationFrom(AbsoluteDate)}
323      * method.</p>
324      * @param since start instant of the measured duration
325      * @param elapsedDuration physically elapsed duration from the <code>since</code>
326      * instant, as measured in a regular time scale
327      * @see #durationFrom(AbsoluteDate)
328      */
329     public AbsoluteDate(final AbsoluteDate since, final double elapsedDuration) {
330 
331         final double sum = since.offset + elapsedDuration;
332         if (Double.isInfinite(sum)) {
333             offset = sum;
334             epoch  = (sum < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
335         } else {
336             // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
337             // the following statements must NOT be simplified, they rely on floating point
338             // arithmetic properties (rounding and representable numbers)
339             // at the end, the EXACT result of addition since.offset + elapsedDuration
340             // is sum + residual, where sum is the closest representable number to the exact
341             // result and residual is the missing part that does not fit in the first number
342             final double oPrime   = sum - elapsedDuration;
343             final double dPrime   = sum - oPrime;
344             final double deltaO   = since.offset - oPrime;
345             final double deltaD   = elapsedDuration - dPrime;
346             final double residual = deltaO + deltaD;
347             final long   dl       = (long) FastMath.floor(sum);
348             offset = (sum - dl) + residual;
349             epoch  = since.epoch  + dl;
350         }
351     }
352 
353     /** Build an instance from an apparent clock offset with respect to another
354      * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
355      * <p>It is important to note that the apparent clock offset <em>is</em> the
356      * difference between two readings on a time scale and <em>not</em> an elapsed
357      * duration. As an example, the apparent clock offset between the two instants
358      * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
359      * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
360      * seconds because a leap second has been introduced at the end of 2005 in this
361      * time scale.</p>
362      * <p>This constructor is the reverse of the {@link #offsetFrom(AbsoluteDate,
363      * TimeScale)} method.</p>
364      * @param reference reference instant
365      * @param apparentOffset apparent clock offset from the reference instant
366      * (difference between two readings in the specified time scale)
367      * @param timeScale time scale with respect to which the offset is defined
368      * @see #offsetFrom(AbsoluteDate, TimeScale)
369      */
370     public AbsoluteDate(final AbsoluteDate reference, final double apparentOffset,
371                         final TimeScale timeScale) {
372         this(new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
373              timeScale);
374     }
375 
376     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
377      * <p>
378      * CCSDS Unsegmented Time Code is defined in the blue book:
379      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
380      * </p>
381      * <p>
382      * If the date to be parsed is formatted using version 3 of the standard
383      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
384      * field introduced in version 4 of the standard is not used, then the
385      * {@code preambleField2} parameter can be set to 0.
386      * </p>
387      * @param preambleField1 first byte of the field specifying the format, often
388      * not transmitted in data interfaces, as it is constant for a given data interface
389      * @param preambleField2 second byte of the field specifying the format
390      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
391      * interfaces, as it is constant for a given data interface (value ignored if presence
392      * not signaled in {@code preambleField1})
393      * @param timeField byte array containing the time code
394      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
395      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
396      * may be null in this case)
397      * @return an instance corresponding to the specified date
398      * @throws OrekitException if preamble is inconsistent with Unsegmented Time Code,
399      * or if it is inconsistent with time field, or if agency epoch is needed but not provided
400      */
401     public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(final byte preambleField1,
402                                                              final byte preambleField2,
403                                                              final byte[] timeField,
404                                                              final AbsoluteDate agencyDefinedEpoch)
405         throws OrekitException {
406 
407         // time code identification and reference epoch
408         final AbsoluteDate epoch;
409         switch (preambleField1 & 0x70) {
410             case 0x10:
411                 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
412                 epoch = CCSDS_EPOCH;
413                 break;
414             case 0x20:
415                 // the reference epoch is agency defined
416                 if (agencyDefinedEpoch == null) {
417                     throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
418                 }
419                 epoch = agencyDefinedEpoch;
420                 break;
421             default :
422                 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
423                                           formatByte(preambleField1));
424         }
425 
426         // time field lengths
427         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
428         int fineTimeLength   = preambleField1 & 0x03;
429 
430         if ((preambleField1 & 0x80) != 0x0) {
431             // there is an additional octet in preamble field
432             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
433             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
434         }
435 
436         if (timeField.length != coarseTimeLength + fineTimeLength) {
437             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
438                                       timeField.length, coarseTimeLength + fineTimeLength);
439         }
440 
441         double seconds = 0;
442         for (int i = 0; i < coarseTimeLength; ++i) {
443             seconds = seconds * 256 + toUnsigned(timeField[i]);
444         }
445         double subseconds = 0;
446         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
447             subseconds = (subseconds + toUnsigned(timeField[i])) / 256;
448         }
449 
450         return new AbsoluteDate(epoch, seconds).shiftedBy(subseconds);
451 
452     }
453 
454     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
455      * <p>
456      * CCSDS Day Segmented Time Code is defined in the blue book:
457      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
458      * </p>
459      * @param preambleField field specifying the format, often not transmitted in
460      * data interfaces, as it is constant for a given data interface
461      * @param timeField byte array containing the time code
462      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
463      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
464      * may be null in this case)
465      * @return an instance corresponding to the specified date
466      * @throws OrekitException if preamble is inconsistent with Day Segmented Time Code,
467      * or if it is inconsistent with time field, or if agency epoch is needed but not provided,
468      * or it UTC time scale cannot be retrieved
469      */
470     public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(final byte preambleField, final byte[] timeField,
471                                                               final DateComponents agencyDefinedEpoch)
472         throws OrekitException {
473 
474         // time code identification
475         if ((preambleField & 0xF0) != 0x40) {
476             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
477                                       formatByte(preambleField));
478         }
479 
480         // reference epoch
481         final DateComponents epoch;
482         if ((preambleField & 0x08) == 0x00) {
483             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
484             epoch = DateComponents.CCSDS_EPOCH;
485         } else {
486             // the reference epoch is agency defined
487             if (agencyDefinedEpoch == null) {
488                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
489             }
490             epoch = agencyDefinedEpoch;
491         }
492 
493         // time field lengths
494         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
495         final int subMillisecondLength = (preambleField & 0x03) << 1;
496         if (subMillisecondLength == 6) {
497             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
498                                       formatByte(preambleField));
499         }
500         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
501             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
502                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
503         }
504 
505 
506         int i   = 0;
507         int day = 0;
508         while (i < daySegmentLength) {
509             day = day * 256 + toUnsigned(timeField[i++]);
510         }
511 
512         long milliInDay = 0l;
513         while (i < daySegmentLength + 4) {
514             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
515         }
516         final int milli   = (int) (milliInDay % 1000l);
517         final int seconds = (int) ((milliInDay - milli) / 1000l);
518 
519         double subMilli = 0;
520         double divisor  = 1;
521         while (i < timeField.length) {
522             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
523             divisor *= 1000;
524         }
525 
526         final DateComponents date = new DateComponents(epoch, day);
527         final TimeComponents time = new TimeComponents(seconds);
528         return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(milli * 1.0e-3 + subMilli / divisor);
529 
530     }
531 
532     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
533      * <p>
534      * CCSDS Calendar Segmented Time Code is defined in the blue book:
535      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
536      * </p>
537      * @param preambleField field specifying the format, often not transmitted in
538      * data interfaces, as it is constant for a given data interface
539      * @param timeField byte array containing the time code
540      * @return an instance corresponding to the specified date
541      * @throws OrekitException if preamble is inconsistent with Calendar Segmented Time Code,
542      * or if it is inconsistent with time field, or it UTC time scale cannot be retrieved
543      */
544     public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField)
545         throws OrekitException {
546 
547         // time code identification
548         if ((preambleField & 0xF0) != 0x50) {
549             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
550                                       formatByte(preambleField));
551         }
552 
553         // time field length
554         final int length = 7 + (preambleField & 0x07);
555         if (length == 14) {
556             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
557                                       formatByte(preambleField));
558         }
559         if (timeField.length != length) {
560             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
561                                       timeField.length, length);
562         }
563 
564         // date part in the first four bytes
565         final DateComponents date;
566         if ((preambleField & 0x08) == 0x00) {
567             // month of year and day of month variation
568             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
569                                       toUnsigned(timeField[2]),
570                                       toUnsigned(timeField[3]));
571         } else {
572             // day of year variation
573             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
574                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
575         }
576 
577         // time part from bytes 5 to last (between 7 and 13 depending on precision)
578         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
579                                                        toUnsigned(timeField[5]),
580                                                        toUnsigned(timeField[6]));
581         double subSecond = 0;
582         double divisor   = 1;
583         for (int i = 7; i < length; ++i) {
584             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
585             divisor *= 100;
586         }
587 
588         return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(subSecond / divisor);
589 
590     }
591 
592     /** Decode a signed byte as an unsigned int value.
593      * @param b byte to decode
594      * @return an unsigned int value
595      */
596     private static int toUnsigned(final byte b) {
597         final int i = (int) b;
598         return (i < 0) ? 256 + i : i;
599     }
600 
601     /** Format a byte as an hex string for error messages.
602      * @param data byte to format
603      * @return a formatted string
604      */
605     private static String formatByte(final byte data) {
606         return "0x" + Integer.toHexString(data).toUpperCase();
607     }
608 
609     /** Build an instance corresponding to a Julian Day date.
610      * @param jd Julian day
611      * @param secondsSinceNoon seconds in the Julian day
612      * (BEWARE, Julian days start at noon, so 0.0 is noon)
613      * @param timeScale time scale in which the seconds in day are defined
614      * @return a new instant
615      */
616     public static AbsoluteDate createJDDate(final int jd, final double secondsSinceNoon,
617                                              final TimeScale timeScale) {
618         return new AbsoluteDate(new DateComponents(DateComponents.JULIAN_EPOCH, jd),
619                                 TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
620     }
621 
622     /** Build an instance corresponding to a Modified Julian Day date.
623      * @param mjd modified Julian day
624      * @param secondsInDay seconds in the day
625      * @param timeScale time scale in which the seconds in day are defined
626      * @return a new instant
627      */
628     public static AbsoluteDate createMJDDate(final int mjd, final double secondsInDay,
629                                              final TimeScale timeScale) {
630         return new AbsoluteDate(new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
631                                 new TimeComponents(secondsInDay),
632                                 timeScale);
633     }
634 
635     /** Build an instance corresponding to a GPS date.
636      * <p>GPS dates are provided as a week number starting at
637      * {@link #GPS_EPOCH GPS epoch} and as a number of milliseconds
638      * since week start.</p>
639      * @param weekNumber week number since {@link #GPS_EPOCH GPS epoch}
640      * @param milliInWeek number of milliseconds since week start
641      * @return a new instant
642      */
643     public static AbsoluteDate createGPSDate(final int weekNumber,
644                                              final double milliInWeek) {
645         final int day = (int) FastMath.floor(milliInWeek / (1000.0 * Constants.JULIAN_DAY));
646         final double secondsInDay = milliInWeek / 1000.0 - day * Constants.JULIAN_DAY;
647         return new AbsoluteDate(new DateComponents(DateComponents.GPS_EPOCH, weekNumber * 7 + day),
648                                 new TimeComponents(secondsInDay),
649                                 TimeScalesFactory.getGPS());
650     }
651 
652     /** Build an instance corresponding to a Julian Epoch (JE).
653      * <p>According to Lieske paper: <a
654      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
655      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
656      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
657      * <pre>
658      * JE = 2000.0 + (JED - 2451545.0) / 365.25
659      * </pre>
660      * <p>
661      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Julian Epoch.
662      * </p>
663      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
664      * @return a new instant
665      * @see #J2000_EPOCH
666      * @see #createBesselianEpoch(double)
667      */
668     public static AbsoluteDate createJulianEpoch(final double julianEpoch) {
669         return new AbsoluteDate(J2000_EPOCH,
670                                 Constants.JULIAN_YEAR * (julianEpoch - 2000.0));
671     }
672 
673     /** Build an instance corresponding to a Besselian Epoch (BE).
674      * <p>According to Lieske paper: <a
675      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
676      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
677      * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
678      * <pre>
679      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
680      * </pre>
681      * <p>
682      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Besselian Epoch.
683      * </p>
684      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
685      * @return a new instant
686      * @see #createJulianEpoch(double)
687      */
688     public static AbsoluteDate createBesselianEpoch(final double besselianEpoch) {
689         return new AbsoluteDate(J2000_EPOCH,
690                                 MathArrays.linearCombination(Constants.BESSELIAN_YEAR, besselianEpoch - 1900,
691                                                              Constants.JULIAN_DAY, -36525,
692                                                              Constants.JULIAN_DAY, 0.31352));
693     }
694 
695     /** Get a time-shifted date.
696      * <p>
697      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
698      * </p>
699      * @param dt time shift in seconds
700      * @return a new date, shifted with respect to instance (which is immutable)
701      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
702      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
703      * @see org.orekit.orbits.Orbit#shiftedBy(double)
704      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
705      */
706     public AbsoluteDate shiftedBy(final double dt) {
707         return new AbsoluteDate(this, dt);
708     }
709 
710     /** Compute the physically elapsed duration between two instants.
711      * <p>The returned duration is the number of seconds physically
712      * elapsed between the two instants, measured in a regular time
713      * scale with respect to surface of the Earth (i.e either the {@link
714      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
715      * GPSScale GPS scale}). It is the only method that gives a
716      * duration with a physical meaning.</p>
717      * <p>This method gives the same result (with less computation)
718      * as calling {@link #offsetFrom(AbsoluteDate, TimeScale)}
719      * with a second argument set to one of the regular scales cited
720      * above.</p>
721      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
722      * double)} constructor.</p>
723      * @param instant instant to subtract from the instance
724      * @return offset in seconds between the two instants (positive
725      * if the instance is posterior to the argument)
726      * @see #offsetFrom(AbsoluteDate, TimeScale)
727      * @see #AbsoluteDate(AbsoluteDate, double)
728      */
729     public double durationFrom(final AbsoluteDate instant) {
730         return (epoch - instant.epoch) + (offset - instant.offset);
731     }
732 
733     /** Compute the apparent clock offset between two instant <em>in the
734      * perspective of a specific {@link TimeScale time scale}</em>.
735      * <p>The offset is the number of seconds counted in the given
736      * time scale between the locations of the two instants, with
737      * all time scale irregularities removed (i.e. considering all
738      * days are exactly 86400 seconds long). This method will give
739      * a result that may not have a physical meaning if the time scale
740      * is irregular. For example since a leap second was introduced at
741      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
742      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
743      * of the corresponding time interval as returned by the {@link
744      * #durationFrom(AbsoluteDate)} method is 2 seconds.</p>
745      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
746      * double, TimeScale)} constructor.</p>
747      * @param instant instant to subtract from the instance
748      * @param timeScale time scale with respect to which the offset should
749      * be computed
750      * @return apparent clock offset in seconds between the two instants
751      * (positive if the instance is posterior to the argument)
752      * @see #durationFrom(AbsoluteDate)
753      * @see #AbsoluteDate(AbsoluteDate, double, TimeScale)
754      */
755     public double offsetFrom(final AbsoluteDate instant, final TimeScale timeScale) {
756         final long   elapsedDurationA = epoch - instant.epoch;
757         final double elapsedDurationB = (offset         + timeScale.offsetFromTAI(this)) -
758                                         (instant.offset + timeScale.offsetFromTAI(instant));
759         return  elapsedDurationA + elapsedDurationB;
760     }
761 
762     /** Compute the offset between two time scales at the current instant.
763      * <p>The offset is defined as <i>l₁-l₂</i>
764      * where <i>l₁</i> is the location of the instant in
765      * the <code>scale1</code> time scale and <i>l₂</i> is the
766      * location of the instant in the <code>scale2</code> time scale.</p>
767      * @param scale1 first time scale
768      * @param scale2 second time scale
769      * @return offset in seconds between the two time scales at the
770      * current instant
771      */
772     public double timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
773         return scale1.offsetFromTAI(this) - scale2.offsetFromTAI(this);
774     }
775 
776     /** Convert the instance to a Java {@link java.util.Date Date}.
777      * <p>Conversion to the Date class induces a loss of precision because
778      * the Date class does not provide sub-millisecond information. Java Dates
779      * are considered to be locations in some times scales.</p>
780      * @param timeScale time scale to use
781      * @return a {@link java.util.Date Date} instance representing the location
782      * of the instant in the time scale
783      */
784     public Date toDate(final TimeScale timeScale) {
785         final double time = epoch + (offset + timeScale.offsetFromTAI(this));
786         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
787     }
788 
789     /** Split the instance into date/time components.
790      * @param timeScale time scale to use
791      * @return date/time components
792      */
793     public DateTimeComponents getComponents(final TimeScale timeScale) {
794 
795         // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
796         // using Møller-Knuth TwoSum algorithm without branching
797         // the following statements must NOT be simplified, they rely on floating point
798         // arithmetic properties (rounding and representable numbers)
799         // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
800         // is sum + residual, where sum is the closest representable number to the exact
801         // result and residual is the missing part that does not fit in the first number
802         final double taiOffset = timeScale.offsetFromTAI(this);
803         final double sum       = offset + taiOffset;
804         final double oPrime    = sum - taiOffset;
805         final double dPrime    = sum - oPrime;
806         final double deltaO    = offset - oPrime;
807         final double deltaD    = taiOffset - dPrime;
808         final double residual  = deltaO + deltaD;
809 
810         // split date and time
811         final long   carry = (long) FastMath.floor(sum);
812         double offset2000B = (sum - carry) + residual;
813         long   offset2000A = epoch + carry + 43200l;
814         if (offset2000B < 0) {
815             offset2000A -= 1;
816             offset2000B += 1;
817         }
818         long time = offset2000A % 86400l;
819         if (time < 0l) {
820             time += 86400l;
821         }
822         final int date = (int) ((offset2000A - time) / 86400l);
823 
824         // extract calendar elements
825         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
826         TimeComponents timeComponents = new TimeComponents((int) time, offset2000B);
827 
828         if (timeScale.insideLeap(this)) {
829             // fix the seconds number to take the leap into account
830             timeComponents = new TimeComponents(timeComponents.getHour(), timeComponents.getMinute(),
831                                                 timeComponents.getSecond() + timeScale.getLeap(this));
832         }
833 
834         // build the components
835         return new DateTimeComponents(dateComponents, timeComponents);
836 
837     }
838 
839     /** Split the instance into date/time components for a local time.
840      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
841      * negative Westward UTC)
842      * @return date/time components
843      * @exception OrekitException if UTC time scale cannot be retrieved
844      * @since 7.2
845      */
846     public DateTimeComponents getComponents(final int minutesFromUTC)
847         throws OrekitException {
848 
849         final DateTimeComponents utcComponents = getComponents(TimeScalesFactory.getUTC());
850 
851         // shift the date according to UTC offset, but WITHOUT touching the seconds,
852         // as they may exceed 60.0 during a leap seconds introduction,
853         // and we want to preserve these special cases
854         final double seconds = utcComponents.getTime().getSecond();
855 
856         int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
857         final int hourShift;
858         if (minute < 0) {
859             hourShift = (minute - 59) / 60;
860         } else if (minute > 59) {
861             hourShift = minute / 60;
862         } else {
863             hourShift = 0;
864         }
865         minute -= 60 * hourShift;
866 
867         int hour = utcComponents.getTime().getHour() + hourShift;
868         final int dayShift;
869         if (hour < 0) {
870             dayShift = (hour - 23) / 24;
871         } else if (hour > 23) {
872             dayShift = hour / 24;
873         } else {
874             dayShift = 0;
875         }
876         hour -= 24 * dayShift;
877 
878         return new DateTimeComponents(new DateComponents(utcComponents.getDate(), dayShift),
879                                       new TimeComponents(hour, minute, seconds, minutesFromUTC));
880 
881     }
882 
883     /** Split the instance into date/time components for a time zone.
884      * @param timeZone time zone
885      * @return date/time components
886      * @exception OrekitException if UTC time scale cannot be retrieved
887      * @since 7.2
888      */
889     public DateTimeComponents getComponents(final TimeZone timeZone)
890         throws OrekitException {
891         final long milliseconds = FastMath.round(1000 * offsetFrom(JAVA_EPOCH, TimeScalesFactory.getUTC()));
892         return getComponents(timeZone.getOffset(milliseconds) / 60000);
893     }
894 
895     /** Compare the instance with another date.
896      * @param date other date to compare the instance to
897      * @return a negative integer, zero, or a positive integer as this date
898      * is before, simultaneous, or after the specified date.
899      */
900     public int compareTo(final AbsoluteDate date) {
901         return Double.compare(durationFrom(date),  0);
902     }
903 
904     /** {@inheritDoc} */
905     public AbsoluteDate getDate() {
906         return this;
907     }
908 
909     /** Check if the instance represent the same time as another instance.
910      * @param date other date
911      * @return true if the instance and the other date refer to the same instant
912      */
913     public boolean equals(final Object date) {
914 
915         if (date == this) {
916             // first fast check
917             return true;
918         }
919 
920         if ((date != null) && (date instanceof AbsoluteDate)) {
921             return durationFrom((AbsoluteDate) date) == 0;
922         }
923 
924         return false;
925 
926     }
927 
928     /** Get a hashcode for this date.
929      * @return hashcode
930      */
931     public int hashCode() {
932         final long l = Double.doubleToLongBits(durationFrom(J2000_EPOCH));
933         return (int) (l ^ (l >>> 32));
934     }
935 
936     /** Get a String representation of the instant location in UTC time scale.
937      * @return a string representation of the instance,
938      * in ISO-8601 format with milliseconds accuracy
939      */
940     public String toString() {
941         try {
942             return toString(TimeScalesFactory.getUTC());
943         } catch (OrekitException oe) {
944             throw new RuntimeException(oe);
945         }
946     }
947 
948     /** Get a String representation of the instant location.
949      * @param timeScale time scale to use
950      * @return a string representation of the instance,
951      * in ISO-8601 format with milliseconds accuracy
952      */
953     public String toString(final TimeScale timeScale) {
954         return getComponents(timeScale).toString(timeScale.minuteDuration(this));
955     }
956 
957     /** Get a String representation of the instant location for a local time.
958      * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
959      * negative Westward UTC).
960      * @return string representation of the instance,
961      * in ISO-8601 format with milliseconds accuracy
962      * @exception OrekitException if UTC time scale cannot be retrieved
963      * @since 7.2
964      */
965     public String toString(final int minutesFromUTC)
966         throws OrekitException {
967         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
968         return getComponents(minutesFromUTC).toString(minuteDuration);
969     }
970 
971     /** Get a String representation of the instant location for a time zone.
972      * @param timeZone time zone
973      * @return string representation of the instance,
974      * in ISO-8601 format with milliseconds accuracy
975      * @exception OrekitException if UTC time scale cannot be retrieved
976      * @since 7.2
977      */
978     public String toString(final TimeZone timeZone)
979         throws OrekitException {
980         final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
981         return getComponents(timeZone).toString(minuteDuration);
982     }
983 
984 }