1 /* Copyright 2002-2018 CS Systèmes d'Information
2 * Licensed to CS Systèmes d'Information (CS) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * CS licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.orekit.time;
18
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 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 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 * @throws OrekitException if preamble is inconsistent with Unsegmented Time Code,
440 * or if it is inconsistent with time field, or if agency epoch is needed but not provided
441 */
442 public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(final byte preambleField1,
443 final byte preambleField2,
444 final byte[] timeField,
445 final AbsoluteDate agencyDefinedEpoch)
446 throws OrekitException {
447
448 // time code identification and reference epoch
449 final AbsoluteDate epoch;
450 switch (preambleField1 & 0x70) {
451 case 0x10:
452 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
453 epoch = CCSDS_EPOCH;
454 break;
455 case 0x20:
456 // the reference epoch is agency defined
457 if (agencyDefinedEpoch == null) {
458 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
459 }
460 epoch = agencyDefinedEpoch;
461 break;
462 default :
463 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
464 formatByte(preambleField1));
465 }
466
467 // time field lengths
468 int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
469 int fineTimeLength = preambleField1 & 0x03;
470
471 if ((preambleField1 & 0x80) != 0x0) {
472 // there is an additional octet in preamble field
473 coarseTimeLength += (preambleField2 & 0x60) >>> 5;
474 fineTimeLength += (preambleField2 & 0x1C) >>> 2;
475 }
476
477 if (timeField.length != coarseTimeLength + fineTimeLength) {
478 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
479 timeField.length, coarseTimeLength + fineTimeLength);
480 }
481
482 double seconds = 0;
483 for (int i = 0; i < coarseTimeLength; ++i) {
484 seconds = seconds * 256 + toUnsigned(timeField[i]);
485 }
486 double subseconds = 0;
487 for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
488 subseconds = (subseconds + toUnsigned(timeField[i])) / 256;
489 }
490
491 return new AbsoluteDate(epoch, seconds).shiftedBy(subseconds);
492
493 }
494
495 /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
496 * <p>
497 * CCSDS Day Segmented Time Code is defined in the blue book:
498 * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
499 * </p>
500 * @param preambleField field specifying the format, often not transmitted in
501 * data interfaces, as it is constant for a given data interface
502 * @param timeField byte array containing the time code
503 * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
504 * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
505 * may be null in this case)
506 * @return an instance corresponding to the specified date
507 * @throws OrekitException if preamble is inconsistent with Day Segmented Time Code,
508 * or if it is inconsistent with time field, or if agency epoch is needed but not provided,
509 * or it UTC time scale cannot be retrieved
510 */
511 public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(final byte preambleField, final byte[] timeField,
512 final DateComponents agencyDefinedEpoch)
513 throws OrekitException {
514
515 // time code identification
516 if ((preambleField & 0xF0) != 0x40) {
517 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
518 formatByte(preambleField));
519 }
520
521 // reference epoch
522 final DateComponents epoch;
523 if ((preambleField & 0x08) == 0x00) {
524 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
525 epoch = DateComponents.CCSDS_EPOCH;
526 } else {
527 // the reference epoch is agency defined
528 if (agencyDefinedEpoch == null) {
529 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
530 }
531 epoch = agencyDefinedEpoch;
532 }
533
534 // time field lengths
535 final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
536 final int subMillisecondLength = (preambleField & 0x03) << 1;
537 if (subMillisecondLength == 6) {
538 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
539 formatByte(preambleField));
540 }
541 if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
542 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
543 timeField.length, daySegmentLength + 4 + subMillisecondLength);
544 }
545
546
547 int i = 0;
548 int day = 0;
549 while (i < daySegmentLength) {
550 day = day * 256 + toUnsigned(timeField[i++]);
551 }
552
553 long milliInDay = 0l;
554 while (i < daySegmentLength + 4) {
555 milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
556 }
557 final int milli = (int) (milliInDay % 1000l);
558 final int seconds = (int) ((milliInDay - milli) / 1000l);
559
560 double subMilli = 0;
561 double divisor = 1;
562 while (i < timeField.length) {
563 subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
564 divisor *= 1000;
565 }
566
567 final DateComponents date = new DateComponents(epoch, day);
568 final TimeComponents time = new TimeComponents(seconds);
569 return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(milli * 1.0e-3 + subMilli / divisor);
570
571 }
572
573 /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
574 * <p>
575 * CCSDS Calendar Segmented Time Code is defined in the blue book:
576 * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
577 * </p>
578 * @param preambleField field specifying the format, often not transmitted in
579 * data interfaces, as it is constant for a given data interface
580 * @param timeField byte array containing the time code
581 * @return an instance corresponding to the specified date
582 * @throws OrekitException if preamble is inconsistent with Calendar Segmented Time Code,
583 * or if it is inconsistent with time field, or it UTC time scale cannot be retrieved
584 */
585 public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField)
586 throws OrekitException {
587
588 // time code identification
589 if ((preambleField & 0xF0) != 0x50) {
590 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
591 formatByte(preambleField));
592 }
593
594 // time field length
595 final int length = 7 + (preambleField & 0x07);
596 if (length == 14) {
597 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
598 formatByte(preambleField));
599 }
600 if (timeField.length != length) {
601 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
602 timeField.length, length);
603 }
604
605 // date part in the first four bytes
606 final DateComponents date;
607 if ((preambleField & 0x08) == 0x00) {
608 // month of year and day of month variation
609 date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
610 toUnsigned(timeField[2]),
611 toUnsigned(timeField[3]));
612 } else {
613 // day of year variation
614 date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
615 toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
616 }
617
618 // time part from bytes 5 to last (between 7 and 13 depending on precision)
619 final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
620 toUnsigned(timeField[5]),
621 toUnsigned(timeField[6]));
622 double subSecond = 0;
623 double divisor = 1;
624 for (int i = 7; i < length; ++i) {
625 subSecond = subSecond * 100 + toUnsigned(timeField[i]);
626 divisor *= 100;
627 }
628
629 return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(subSecond / divisor);
630
631 }
632
633 /** Decode a signed byte as an unsigned int value.
634 * @param b byte to decode
635 * @return an unsigned int value
636 */
637 private static int toUnsigned(final byte b) {
638 final int i = (int) b;
639 return (i < 0) ? 256 + i : i;
640 }
641
642 /** Format a byte as an hex string for error messages.
643 * @param data byte to format
644 * @return a formatted string
645 */
646 private static String formatByte(final byte data) {
647 return "0x" + Integer.toHexString(data).toUpperCase();
648 }
649
650 /** Build an instance corresponding to a Julian Day date.
651 * @param jd Julian day
652 * @param secondsSinceNoon seconds in the Julian day
653 * (BEWARE, Julian days start at noon, so 0.0 is noon)
654 * @param timeScale time scale in which the seconds in day are defined
655 * @return a new instant
656 */
657 public static AbsoluteDate createJDDate(final int jd, final double secondsSinceNoon,
658 final TimeScale timeScale) {
659 return new AbsoluteDate(new DateComponents(DateComponents.JULIAN_EPOCH, jd),
660 TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
661 }
662
663 /** Build an instance corresponding to a Modified Julian Day date.
664 * @param mjd modified Julian day
665 * @param secondsInDay seconds in the day
666 * @param timeScale time scale in which the seconds in day are defined
667 * @return a new instant
668 * @exception OrekitIllegalArgumentException if seconds number is out of range
669 */
670 public static AbsoluteDate createMJDDate(final int mjd, final double secondsInDay,
671 final TimeScale timeScale)
672 throws OrekitIllegalArgumentException {
673 final DateComponents dc = new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd);
674 final TimeComponents tc;
675 if (secondsInDay >= Constants.JULIAN_DAY) {
676 // check we are really allowed to use this number of seconds
677 final int secondsA = 86399; // 23:59:59, i.e. 59s in the last minute of the day
678 final double secondsB = secondsInDay - secondsA;
679 final TimeComponents safeTC = new TimeComponents(secondsA, 0.0);
680 final AbsoluteDate safeDate = new AbsoluteDate(dc, safeTC, timeScale);
681 if (timeScale.minuteDuration(safeDate) > 59 + secondsB) {
682 // we are within the last minute of the day, the number of seconds is OK
683 return safeDate.shiftedBy(secondsB);
684 } else {
685 // let TimeComponents trigger an OrekitIllegalArgumentException
686 // for the wrong number of seconds
687 tc = new TimeComponents(secondsA, secondsB);
688 }
689 } else {
690 tc = new TimeComponents(secondsInDay);
691 }
692
693 // create the date
694 return new AbsoluteDate(dc, tc, timeScale);
695
696 }
697
698
699 /** Build an instance corresponding to a GPS date.
700 * <p>GPS dates are provided as a week number starting at
701 * {@link #GPS_EPOCH GPS epoch} and as a number of milliseconds
702 * since week start.</p>
703 * @param weekNumber week number since {@link #GPS_EPOCH GPS epoch}
704 * @param milliInWeek number of milliseconds since week start
705 * @return a new instant
706 */
707 public static AbsoluteDate createGPSDate(final int weekNumber,
708 final double milliInWeek) {
709 final int day = (int) FastMath.floor(milliInWeek / (1000.0 * Constants.JULIAN_DAY));
710 final double secondsInDay = milliInWeek / 1000.0 - day * Constants.JULIAN_DAY;
711 return new AbsoluteDate(new DateComponents(DateComponents.GPS_EPOCH, weekNumber * 7 + day),
712 new TimeComponents(secondsInDay),
713 TimeScalesFactory.getGPS());
714 }
715
716 /** Build an instance corresponding to a Julian Epoch (JE).
717 * <p>According to Lieske paper: <a
718 * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
719 * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
720 * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
721 * <pre>
722 * JE = 2000.0 + (JED - 2451545.0) / 365.25
723 * </pre>
724 * <p>
725 * This method reverts the formula above and computes an {@code AbsoluteDate} from the Julian Epoch.
726 * </p>
727 * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
728 * @return a new instant
729 * @see #J2000_EPOCH
730 * @see #createBesselianEpoch(double)
731 */
732 public static AbsoluteDate createJulianEpoch(final double julianEpoch) {
733 return new AbsoluteDate(J2000_EPOCH,
734 Constants.JULIAN_YEAR * (julianEpoch - 2000.0));
735 }
736
737 /** Build an instance corresponding to a Besselian Epoch (BE).
738 * <p>According to Lieske paper: <a
739 * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
740 * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
741 * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
742 * <pre>
743 * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
744 * </pre>
745 * <p>
746 * This method reverts the formula above and computes an {@code AbsoluteDate} from the Besselian Epoch.
747 * </p>
748 * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
749 * @return a new instant
750 * @see #createJulianEpoch(double)
751 */
752 public static AbsoluteDate createBesselianEpoch(final double besselianEpoch) {
753 return new AbsoluteDate(J2000_EPOCH,
754 MathArrays.linearCombination(Constants.BESSELIAN_YEAR, besselianEpoch - 1900,
755 Constants.JULIAN_DAY, -36525,
756 Constants.JULIAN_DAY, 0.31352));
757 }
758
759 /** Get a time-shifted date.
760 * <p>
761 * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
762 * </p>
763 * @param dt time shift in seconds
764 * @return a new date, shifted with respect to instance (which is immutable)
765 * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
766 * @see org.orekit.attitudes.Attitude#shiftedBy(double)
767 * @see org.orekit.orbits.Orbit#shiftedBy(double)
768 * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
769 */
770 public AbsoluteDate shiftedBy(final double dt) {
771 return new AbsoluteDate(this, dt);
772 }
773
774 /** Compute the physically elapsed duration between two instants.
775 * <p>The returned duration is the number of seconds physically
776 * elapsed between the two instants, measured in a regular time
777 * scale with respect to surface of the Earth (i.e either the {@link
778 * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
779 * GPSScale GPS scale}). It is the only method that gives a
780 * duration with a physical meaning.</p>
781 * <p>This method gives the same result (with less computation)
782 * as calling {@link #offsetFrom(AbsoluteDate, TimeScale)}
783 * with a second argument set to one of the regular scales cited
784 * above.</p>
785 * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
786 * double)} constructor.</p>
787 * @param instant instant to subtract from the instance
788 * @return offset in seconds between the two instants (positive
789 * if the instance is posterior to the argument)
790 * @see #offsetFrom(AbsoluteDate, TimeScale)
791 * @see #AbsoluteDate(AbsoluteDate, double)
792 */
793 public double durationFrom(final AbsoluteDate instant) {
794 return (epoch - instant.epoch) + (offset - instant.offset);
795 }
796
797 /** Compute the apparent clock offset between two instant <em>in the
798 * perspective of a specific {@link TimeScale time scale}</em>.
799 * <p>The offset is the number of seconds counted in the given
800 * time scale between the locations of the two instants, with
801 * all time scale irregularities removed (i.e. considering all
802 * days are exactly 86400 seconds long). This method will give
803 * a result that may not have a physical meaning if the time scale
804 * is irregular. For example since a leap second was introduced at
805 * the end of 2005, the apparent offset between 2005-12-31T23:59:59
806 * and 2006-01-01T00:00:00 is 1 second, but the physical duration
807 * of the corresponding time interval as returned by the {@link
808 * #durationFrom(AbsoluteDate)} method is 2 seconds.</p>
809 * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
810 * double, TimeScale)} constructor.</p>
811 * @param instant instant to subtract from the instance
812 * @param timeScale time scale with respect to which the offset should
813 * be computed
814 * @return apparent clock offset in seconds between the two instants
815 * (positive if the instance is posterior to the argument)
816 * @see #durationFrom(AbsoluteDate)
817 * @see #AbsoluteDate(AbsoluteDate, double, TimeScale)
818 */
819 public double offsetFrom(final AbsoluteDate instant, final TimeScale timeScale) {
820 final long elapsedDurationA = epoch - instant.epoch;
821 final double elapsedDurationB = (offset + timeScale.offsetFromTAI(this)) -
822 (instant.offset + timeScale.offsetFromTAI(instant));
823 return elapsedDurationA + elapsedDurationB;
824 }
825
826 /** Compute the offset between two time scales at the current instant.
827 * <p>The offset is defined as <i>l₁-l₂</i>
828 * where <i>l₁</i> is the location of the instant in
829 * the <code>scale1</code> time scale and <i>l₂</i> is the
830 * location of the instant in the <code>scale2</code> time scale.</p>
831 * @param scale1 first time scale
832 * @param scale2 second time scale
833 * @return offset in seconds between the two time scales at the
834 * current instant
835 */
836 public double timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
837 return scale1.offsetFromTAI(this) - scale2.offsetFromTAI(this);
838 }
839
840 /** Convert the instance to a Java {@link java.util.Date Date}.
841 * <p>Conversion to the Date class induces a loss of precision because
842 * the Date class does not provide sub-millisecond information. Java Dates
843 * are considered to be locations in some times scales.</p>
844 * @param timeScale time scale to use
845 * @return a {@link java.util.Date Date} instance representing the location
846 * of the instant in the time scale
847 */
848 public Date toDate(final TimeScale timeScale) {
849 final double time = epoch + (offset + timeScale.offsetFromTAI(this));
850 return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
851 }
852
853 /** Split the instance into date/time components.
854 * @param timeScale time scale to use
855 * @return date/time components
856 */
857 public DateTimeComponents getComponents(final TimeScale timeScale) {
858
859 if (Double.isInfinite(offset)) {
860 // special handling for past and future infinity
861 if (offset < 0) {
862 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
863 } else {
864 return new DateTimeComponents(DateComponents.MAX_EPOCH,
865 new TimeComponents(23, 59, 59.999));
866 }
867 }
868
869 // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
870 // using Møller-Knuth TwoSum algorithm without branching
871 // the following statements must NOT be simplified, they rely on floating point
872 // arithmetic properties (rounding and representable numbers)
873 // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
874 // is sum + residual, where sum is the closest representable number to the exact
875 // result and residual is the missing part that does not fit in the first number
876 final double taiOffset = timeScale.offsetFromTAI(this);
877 final double sum = offset + taiOffset;
878 final double oPrime = sum - taiOffset;
879 final double dPrime = sum - oPrime;
880 final double deltaO = offset - oPrime;
881 final double deltaD = taiOffset - dPrime;
882 final double residual = deltaO + deltaD;
883
884 // split date and time
885 final long carry = (long) FastMath.floor(sum);
886 double offset2000B = (sum - carry) + residual;
887 long offset2000A = epoch + carry + 43200l;
888 if (offset2000B < 0) {
889 offset2000A -= 1;
890 offset2000B += 1;
891 }
892 long time = offset2000A % 86400l;
893 if (time < 0l) {
894 time += 86400l;
895 }
896 final int date = (int) ((offset2000A - time) / 86400l);
897
898 // extract calendar elements
899 final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
900 TimeComponents timeComponents = new TimeComponents((int) time, offset2000B);
901
902 if (timeScale.insideLeap(this)) {
903 // fix the seconds number to take the leap into account
904 timeComponents = new TimeComponents(timeComponents.getHour(), timeComponents.getMinute(),
905 timeComponents.getSecond() + timeScale.getLeap(this));
906 }
907
908 // build the components
909 return new DateTimeComponents(dateComponents, timeComponents);
910
911 }
912
913 /** Split the instance into date/time components for a local time.
914 * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
915 * negative Westward UTC)
916 * @return date/time components
917 * @exception OrekitException if UTC time scale cannot be retrieved
918 * @since 7.2
919 */
920 public DateTimeComponents getComponents(final int minutesFromUTC)
921 throws OrekitException {
922
923 final DateTimeComponents utcComponents = getComponents(TimeScalesFactory.getUTC());
924
925 // shift the date according to UTC offset, but WITHOUT touching the seconds,
926 // as they may exceed 60.0 during a leap seconds introduction,
927 // and we want to preserve these special cases
928 final double seconds = utcComponents.getTime().getSecond();
929
930 int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
931 final int hourShift;
932 if (minute < 0) {
933 hourShift = (minute - 59) / 60;
934 } else if (minute > 59) {
935 hourShift = minute / 60;
936 } else {
937 hourShift = 0;
938 }
939 minute -= 60 * hourShift;
940
941 int hour = utcComponents.getTime().getHour() + hourShift;
942 final int dayShift;
943 if (hour < 0) {
944 dayShift = (hour - 23) / 24;
945 } else if (hour > 23) {
946 dayShift = hour / 24;
947 } else {
948 dayShift = 0;
949 }
950 hour -= 24 * dayShift;
951
952 return new DateTimeComponents(new DateComponents(utcComponents.getDate(), dayShift),
953 new TimeComponents(hour, minute, seconds, minutesFromUTC));
954
955 }
956
957 /** Split the instance into date/time components for a time zone.
958 * @param timeZone time zone
959 * @return date/time components
960 * @exception OrekitException if UTC time scale cannot be retrieved
961 * @since 7.2
962 */
963 public DateTimeComponents getComponents(final TimeZone timeZone)
964 throws OrekitException {
965 final long milliseconds = FastMath.round(1000 * offsetFrom(JAVA_EPOCH, TimeScalesFactory.getUTC()));
966 return getComponents(timeZone.getOffset(milliseconds) / 60000);
967 }
968
969 /** Compare the instance with another date.
970 * @param date other date to compare the instance to
971 * @return a negative integer, zero, or a positive integer as this date
972 * is before, simultaneous, or after the specified date.
973 */
974 public int compareTo(final AbsoluteDate date) {
975 return Double.compare(durationFrom(date), 0);
976 }
977
978 /** {@inheritDoc} */
979 public AbsoluteDate getDate() {
980 return this;
981 }
982
983 /** Check if the instance represent the same time as another instance.
984 * @param date other date
985 * @return true if the instance and the other date refer to the same instant
986 */
987 public boolean equals(final Object date) {
988
989 if (date == this) {
990 // first fast check
991 return true;
992 }
993
994 if ((date != null) && (date instanceof AbsoluteDate)) {
995 return durationFrom((AbsoluteDate) date) == 0;
996 }
997
998 return false;
999
1000 }
1001
1002 /** Get a hashcode for this date.
1003 * @return hashcode
1004 */
1005 public int hashCode() {
1006 final long l = Double.doubleToLongBits(durationFrom(J2000_EPOCH));
1007 return (int) (l ^ (l >>> 32));
1008 }
1009
1010 /** Get a String representation of the instant location in UTC time scale.
1011 * @return a string representation of the instance,
1012 * in ISO-8601 format with milliseconds accuracy
1013 */
1014 public String toString() {
1015 try {
1016 return toString(TimeScalesFactory.getUTC());
1017 } catch (OrekitException oe) {
1018 throw new RuntimeException(oe);
1019 }
1020 }
1021
1022 /** Get a String representation of the instant location.
1023 * @param timeScale time scale to use
1024 * @return a string representation of the instance,
1025 * in ISO-8601 format with milliseconds accuracy
1026 */
1027 public String toString(final TimeScale timeScale) {
1028 return getComponents(timeScale).toString(timeScale.minuteDuration(this));
1029 }
1030
1031 /** Get a String representation of the instant location for a local time.
1032 * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
1033 * negative Westward UTC).
1034 * @return string representation of the instance,
1035 * in ISO-8601 format with milliseconds accuracy
1036 * @exception OrekitException if UTC time scale cannot be retrieved
1037 * @since 7.2
1038 */
1039 public String toString(final int minutesFromUTC)
1040 throws OrekitException {
1041 final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
1042 return getComponents(minutesFromUTC).toString(minuteDuration);
1043 }
1044
1045 /** Get a String representation of the instant location for a time zone.
1046 * @param timeZone time zone
1047 * @return string representation of the instance,
1048 * in ISO-8601 format with milliseconds accuracy
1049 * @exception OrekitException if UTC time scale cannot be retrieved
1050 * @since 7.2
1051 */
1052 public String toString(final TimeZone timeZone)
1053 throws OrekitException {
1054 final int minuteDuration = TimeScalesFactory.getUTC().minuteDuration(this);
1055 return getComponents(timeZone).toString(minuteDuration);
1056 }
1057
1058 }