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