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