1 /* Copyright 2002-2020 CS GROUP
2 * Licensed to CS GROUP (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.orekit.annotation.DefaultDataContext;
25 import org.orekit.data.DataContext;
26 import org.orekit.errors.OrekitException;
27 import org.orekit.errors.OrekitIllegalArgumentException;
28 import org.orekit.errors.OrekitMessages;
29 import org.orekit.utils.Constants;
30
31
32 /** This class represents a specific instant in time.
33
34 * <p>Instances of this class are considered to be absolute in the sense
35 * that each one represent the occurrence of some event and can be compared
36 * to other instances or located in <em>any</em> {@link TimeScale time scale}. In
37 * other words the different locations of an event with respect to two different
38 * time scales (say {@link TAIScale TAI} and {@link UTCScale UTC} for example) are
39 * simply different perspective related to a single object. Only one
40 * <code>AbsoluteDate</code> instance is needed, both representations being available
41 * from this single instance by specifying the time scales as parameter when calling
42 * the ad-hoc methods.</p>
43 *
44 * <p>Since an instance is not bound to a specific time-scale, all methods related
45 * to the location of the date within some time scale require to provide the time
46 * scale as an argument. It is therefore possible to define a date in one time scale
47 * and to use it in another one. An example of such use is to read a date from a file
48 * in UTC and write it in another file in TAI. This can be done as follows:</p>
49 * <pre>
50 * DateTimeComponents utcComponents = readNextDate();
51 * AbsoluteDate date = new AbsoluteDate(utcComponents, TimeScalesFactory.getUTC());
52 * writeNextDate(date.getComponents(TimeScalesFactory.getTAI()));
53 * </pre>
54 *
55 * <p>Two complementary views are available:</p>
56 * <ul>
57 * <li><p>location view (mainly for input/output or conversions)</p>
58 * <p>locations represent the coordinate of one event with respect to a
59 * {@link TimeScale time scale}. The related methods are {@link
60 * #AbsoluteDate(DateComponents, TimeComponents, TimeScale)}, {@link
61 * #AbsoluteDate(int, int, int, int, int, double, TimeScale)}, {@link
62 * #AbsoluteDate(int, int, int, TimeScale)}, {@link #AbsoluteDate(Date,
63 * TimeScale)}, {@link #parseCCSDSCalendarSegmentedTimeCode(byte, byte[])},
64 * {@link #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 #QZSS_EPOCH}
83 * {@link #J2000_EPOCH}, {@link #JAVA_EPOCH}.
84 * There are also two factory methods {@link #createJulianEpoch(double)}
85 * and {@link #createBesselianEpoch(double)} that can be used to compute other reference
86 * epochs like J1900.0 or B1950.0.
87 * In addition to these reference epochs, two other constants are defined for convenience:
88 * {@link #PAST_INFINITY} and {@link #FUTURE_INFINITY}, which can be used either as dummy
89 * dates when a date is not yet initialized, or for initialization of loops searching for
90 * a min or max date.
91 * </p>
92 * <p>
93 * Instances of the <code>AbsoluteDate</code> class are guaranteed to be immutable.
94 * </p>
95 * @author Luc Maisonobe
96 * @author Evan Ward
97 * @see TimeScale
98 * @see TimeStamped
99 * @see ChronologicalComparator
100 */
101 public class AbsoluteDate
102 implements TimeStamped, TimeShiftable<AbsoluteDate>, Comparable<AbsoluteDate>, Serializable {
103
104 /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
105 * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
106 * follow the astronomical conventions and consider a year 0 between
107 * years -1 and +1, hence this reference date lies in year -4712 and not
108 * in year -4713 as can be seen in other documents or programs that obey
109 * a different convention (for example the <code>convcal</code> utility).</p>
110 *
111 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
112 *
113 * @see TimeScales#getJulianEpoch()
114 */
115 @DefaultDataContext
116 public static final AbsoluteDate JULIAN_EPOCH =
117 DataContext.getDefault().getTimeScales().getJulianEpoch();
118
119 /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time.
120 *
121 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
122 *
123 * @see TimeScales#getModifiedJulianEpoch()
124 */
125 @DefaultDataContext
126 public static final AbsoluteDate MODIFIED_JULIAN_EPOCH =
127 DataContext.getDefault().getTimeScales().getModifiedJulianEpoch();
128
129 /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time.
130 *
131 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
132 *
133 * @see TimeScales#getFiftiesEpoch()
134 */
135 @DefaultDataContext
136 public static final AbsoluteDate FIFTIES_EPOCH =
137 DataContext.getDefault().getTimeScales().getFiftiesEpoch();
138
139 /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
140 * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC).
141 *
142 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
143 *
144 * @see TimeScales#getCcsdsEpoch()
145 */
146 @DefaultDataContext
147 public static final AbsoluteDate CCSDS_EPOCH =
148 DataContext.getDefault().getTimeScales().getCcsdsEpoch();
149
150 /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 GST.
151 *
152 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
153 *
154 * @see TimeScales#getGalileoEpoch()
155 */
156 @DefaultDataContext
157 public static final AbsoluteDate GALILEO_EPOCH =
158 DataContext.getDefault().getTimeScales().getGalileoEpoch();
159
160 /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time.
161 *
162 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
163 *
164 * @see TimeScales#getGpsEpoch()
165 */
166 @DefaultDataContext
167 public static final AbsoluteDate GPS_EPOCH =
168 DataContext.getDefault().getTimeScales().getGpsEpoch();
169
170 /** Reference epoch for QZSS weeks: 1980-01-06T00:00:00 QZSS time.
171 *
172 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
173 *
174 * @see TimeScales#getQzssEpoch()
175 */
176 @DefaultDataContext
177 public static final AbsoluteDate QZSS_EPOCH =
178 DataContext.getDefault().getTimeScales().getQzssEpoch();
179
180 /** Reference epoch for IRNSS weeks: 1999-08-22T00:00:00 IRNSS time.
181 *
182 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
183 *
184 * @see TimeScales#getIrnssEpoch()
185 */
186 @DefaultDataContext
187 public static final AbsoluteDate IRNSS_EPOCH =
188 DataContext.getDefault().getTimeScales().getIrnssEpoch();
189
190 /** Reference epoch for BeiDou weeks: 2006-01-01T00:00:00 UTC.
191 *
192 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
193 *
194 * @see TimeScales#getBeidouEpoch()
195 */
196 @DefaultDataContext
197 public static final AbsoluteDate BEIDOU_EPOCH =
198 DataContext.getDefault().getTimeScales().getBeidouEpoch();
199
200 /** Reference epoch for GLONASS four-year interval number: 1996-01-01T00:00:00 GLONASS time.
201 * <p>By convention, TGLONASS = UTC + 3 hours.</p>
202 *
203 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
204 *
205 * @see TimeScales#getGlonassEpoch()
206 */
207 @DefaultDataContext
208 public static final AbsoluteDate GLONASS_EPOCH =
209 DataContext.getDefault().getTimeScales().getGlonassEpoch();
210
211 /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
212 * @see #createJulianEpoch(double)
213 * @see #createBesselianEpoch(double)
214 *
215 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
216 *
217 * @see TimeScales#getJ2000Epoch()
218 */
219 @DefaultDataContext
220 public static final AbsoluteDate J2000_EPOCH = // TODO
221 DataContext.getDefault().getTimeScales().getJ2000Epoch();
222
223 /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
224 * <p>
225 * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
226 * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
227 * </p>
228 *
229 * <p>This constant uses the {@link DataContext#getDefault() default data context}.
230 *
231 * @see TimeScales#getJavaEpoch()
232 */
233 @DefaultDataContext
234 public static final AbsoluteDate JAVA_EPOCH =
235 DataContext.getDefault().getTimeScales().getJavaEpoch();
236
237 /**
238 * An arbitrary finite date. Uses when a non-null date is needed but its value doesn't
239 * matter.
240 */
241 public static final AbsoluteDate">AbsoluteDate ARBITRARY_EPOCH = new AbsoluteDate(0, 0);
242
243 /** Dummy date at infinity in the past direction.
244 * @see TimeScales#getPastInfinity()
245 */
246 public static final AbsoluteDate PAST_INFINITY = ARBITRARY_EPOCH.shiftedBy(Double.NEGATIVE_INFINITY);
247
248 /** Dummy date at infinity in the future direction.
249 * @see TimeScales#getFutureInfinity()
250 */
251 public static final AbsoluteDate FUTURE_INFINITY = ARBITRARY_EPOCH.shiftedBy(Double.POSITIVE_INFINITY);
252
253 /** Serializable UID. */
254 private static final long serialVersionUID = 617061803741806846L;
255
256 /** Reference epoch in seconds from 2000-01-01T12:00:00 TAI.
257 * <p>Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.</p> */
258 private final long epoch;
259
260 /** Offset from the reference epoch in seconds. */
261 private final double offset;
262
263 /** Create an instance with a default value ({@link #J2000_EPOCH}).
264 *
265 * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
266 *
267 * @see #AbsoluteDate(DateTimeComponents, TimeScale)
268 */
269 @DefaultDataContext
270 public AbsoluteDate() {
271 epoch = J2000_EPOCH.epoch;
272 offset = J2000_EPOCH.offset;
273 }
274
275 /** Build an instance from a location (parsed from a string) in a {@link TimeScale time scale}.
276 * <p>
277 * The supported formats for location are mainly the ones defined in ISO-8601 standard,
278 * the exact subset is explained in {@link DateTimeComponents#parseDateTime(String)},
279 * {@link DateComponents#parseDate(String)} and {@link TimeComponents#parseTime(String)}.
280 * </p>
281 * <p>
282 * As CCSDS ASCII calendar segmented time code is a trimmed down version of ISO-8601,
283 * it is also supported by this constructor.
284 * </p>
285 * @param location location in the time scale, must be in a supported format
286 * @param timeScale time scale
287 * @exception IllegalArgumentException if location string is not in a supported format
288 */
289 public AbsoluteDate(final String location, final TimeScale timeScale) {
290 this(DateTimeComponents.parseDateTime(location), timeScale);
291 }
292
293 /** Build an instance from a location in a {@link TimeScale time scale}.
294 * @param location location in the time scale
295 * @param timeScale time scale
296 */
297 public AbsoluteDate(final DateTimeComponents location, final TimeScale timeScale) {
298 this(location.getDate(), location.getTime(), timeScale);
299 }
300
301 /** Build an instance from a location in a {@link TimeScale time scale}.
302 * @param date date location in the time scale
303 * @param time time location in the time scale
304 * @param timeScale time scale
305 */
306 public AbsoluteDate(final DateComponents date, final TimeComponents time,
307 final TimeScale timeScale) {
308
309 final double seconds = time.getSecond();
310 final double tsOffset = timeScale.offsetToTAI(date, time);
311
312 // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
313 // the following statements must NOT be simplified, they rely on floating point
314 // arithmetic properties (rounding and representable numbers)
315 // at the end, the EXACT result of addition seconds + tsOffset
316 // is sum + residual, where sum is the closest representable number to the exact
317 // result and residual is the missing part that does not fit in the first number
318 final double sum = seconds + tsOffset;
319 final double sPrime = sum - tsOffset;
320 final double tPrime = sum - sPrime;
321 final double deltaS = seconds - sPrime;
322 final double deltaT = tsOffset - tPrime;
323 final double residual = deltaS + deltaT;
324 final long dl = (long) FastMath.floor(sum);
325
326 offset = (sum - dl) + residual;
327 epoch = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l +
328 time.getMinute() - time.getMinutesFromUTC() - 720l) + dl;
329
330 }
331
332 /** Build an instance from a location in a {@link TimeScale time scale}.
333 * @param year year number (may be 0 or negative for BC years)
334 * @param month month number from 1 to 12
335 * @param day day number from 1 to 31
336 * @param hour hour number from 0 to 23
337 * @param minute minute number from 0 to 59
338 * @param second second number from 0.0 to 60.0 (excluded)
339 * @param timeScale time scale
340 * @exception IllegalArgumentException if inconsistent arguments
341 * are given (parameters out of range)
342 */
343 public AbsoluteDate(final int year, final int month, final int day,
344 final int hour, final int minute, final double second,
345 final TimeScale timeScale) throws IllegalArgumentException {
346 this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
347 }
348
349 /** Build an instance from a location in a {@link TimeScale time scale}.
350 * @param year year number (may be 0 or negative for BC years)
351 * @param month month enumerate
352 * @param day day number from 1 to 31
353 * @param hour hour number from 0 to 23
354 * @param minute minute number from 0 to 59
355 * @param second second number from 0.0 to 60.0 (excluded)
356 * @param timeScale time scale
357 * @exception IllegalArgumentException if inconsistent arguments
358 * are given (parameters out of range)
359 */
360 public AbsoluteDate(final int year, final Month month, final int day,
361 final int hour, final int minute, final double second,
362 final TimeScale timeScale) throws IllegalArgumentException {
363 this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
364 }
365
366 /** Build an instance from a location in a {@link TimeScale time scale}.
367 * <p>The hour is set to 00:00:00.000.</p>
368 * @param date date location in the time scale
369 * @param timeScale time scale
370 * @exception IllegalArgumentException if inconsistent arguments
371 * are given (parameters out of range)
372 */
373 public AbsoluteDate(final DateComponents date, final TimeScale timeScale)
374 throws IllegalArgumentException {
375 this(date, TimeComponents.H00, timeScale);
376 }
377
378 /** Build an instance from a location in a {@link TimeScale time scale}.
379 * <p>The hour is set to 00:00:00.000.</p>
380 * @param year year number (may be 0 or negative for BC years)
381 * @param month month number from 1 to 12
382 * @param day day number from 1 to 31
383 * @param timeScale time scale
384 * @exception IllegalArgumentException if inconsistent arguments
385 * are given (parameters out of range)
386 */
387 public AbsoluteDate(final int year, final int month, final int day,
388 final TimeScale timeScale) throws IllegalArgumentException {
389 this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
390 }
391
392 /** Build an instance from a location in a {@link TimeScale time scale}.
393 * <p>The hour is set to 00:00:00.000.</p>
394 * @param year year number (may be 0 or negative for BC years)
395 * @param month month enumerate
396 * @param day day number from 1 to 31
397 * @param timeScale time scale
398 * @exception IllegalArgumentException if inconsistent arguments
399 * are given (parameters out of range)
400 */
401 public AbsoluteDate(final int year, final Month month, final int day,
402 final TimeScale timeScale) throws IllegalArgumentException {
403 this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
404 }
405
406 /** Build an instance from a location in a {@link TimeScale time scale}.
407 * @param location location in the time scale
408 * @param timeScale time scale
409 */
410 public AbsoluteDate(final Date location, final TimeScale timeScale) {
411 this(new DateComponents(DateComponents.JAVA_EPOCH,
412 (int) (location.getTime() / 86400000l)),
413 millisToTimeComponents((int) (location.getTime() % 86400000l)),
414 timeScale);
415 }
416
417 /** Build an instance from an elapsed duration since to another instant.
418 * <p>It is important to note that the elapsed duration is <em>not</em>
419 * the difference between two readings on a time scale. As an example,
420 * the duration between the two instants leading to the readings
421 * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
422 * time scale is <em>not</em> 1 second, but a stop watch would have measured
423 * an elapsed duration of 2 seconds between these two instances because a leap
424 * second was introduced at the end of 2005 in this time scale.</p>
425 * <p>This constructor is the reverse of the {@link #durationFrom(AbsoluteDate)}
426 * method.</p>
427 * @param since start instant of the measured duration
428 * @param elapsedDuration physically elapsed duration from the <code>since</code>
429 * instant, as measured in a regular time scale
430 * @see #durationFrom(AbsoluteDate)
431 */
432 public AbsoluteDatetml#AbsoluteDate">AbsoluteDate(final AbsoluteDate since, final double elapsedDuration) {
433
434 final double sum = since.offset + elapsedDuration;
435 if (Double.isInfinite(sum)) {
436 offset = sum;
437 epoch = (sum < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
438 } else {
439 // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
440 // the following statements must NOT be simplified, they rely on floating point
441 // arithmetic properties (rounding and representable numbers)
442 // at the end, the EXACT result of addition since.offset + elapsedDuration
443 // is sum + residual, where sum is the closest representable number to the exact
444 // result and residual is the missing part that does not fit in the first number
445 final double oPrime = sum - elapsedDuration;
446 final double dPrime = sum - oPrime;
447 final double deltaO = since.offset - oPrime;
448 final double deltaD = elapsedDuration - dPrime;
449 final double residual = deltaO + deltaD;
450 final long dl = (long) FastMath.floor(sum);
451 offset = (sum - dl) + residual;
452 epoch = since.epoch + dl;
453 }
454 }
455
456 /** Build an instance from an apparent clock offset with respect to another
457 * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
458 * <p>It is important to note that the apparent clock offset <em>is</em> the
459 * difference between two readings on a time scale and <em>not</em> an elapsed
460 * duration. As an example, the apparent clock offset between the two instants
461 * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
462 * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
463 * seconds because a leap second has been introduced at the end of 2005 in this
464 * time scale.</p>
465 * <p>This constructor is the reverse of the {@link #offsetFrom(AbsoluteDate,
466 * TimeScale)} method.</p>
467 * @param reference reference instant
468 * @param apparentOffset apparent clock offset from the reference instant
469 * (difference between two readings in the specified time scale)
470 * @param timeScale time scale with respect to which the offset is defined
471 * @see #offsetFrom(AbsoluteDate, TimeScale)
472 */
473 public AbsoluteDatetml#AbsoluteDate">AbsoluteDate(final AbsoluteDate reference, final double apparentOffset,
474 final TimeScale timeScale) {
475 this(new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
476 timeScale);
477 }
478
479 /** Build a date from its internal components.
480 * <p>
481 * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
482 * </p>
483 * @param epoch reference epoch in seconds from 2000-01-01T12:00:00 TAI.
484 * (beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT)
485 * @param offset offset from the reference epoch in seconds (must be
486 * between 0.0 included and 1.0 excluded)
487 * @since 9.0
488 */
489 AbsoluteDate(final long epoch, final double offset) {
490 this.epoch = epoch;
491 this.offset = offset;
492 }
493
494 /** Extract time components from a number of milliseconds within the day.
495 * @param millisInDay number of milliseconds within the day
496 * @return time components
497 */
498 private static TimeComponents millisToTimeComponents(final int millisInDay) {
499 return new TimeComponents(millisInDay / 1000, 0.001 * (millisInDay % 1000));
500 }
501
502 /** Get the reference epoch in seconds from 2000-01-01T12:00:00 TAI.
503 * <p>
504 * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
505 * </p>
506 * <p>
507 * Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.
508 * </p>
509 * @return reference epoch in seconds from 2000-01-01T12:00:00 TAI
510 * @since 9.0
511 */
512 long getEpoch() {
513 return epoch;
514 }
515
516 /** Get the offset from the reference epoch in seconds.
517 * <p>
518 * This method is reserved for internal used (for example by {@link FieldAbsoluteDate}).
519 * </p>
520 * @return offset from the reference epoch in seconds
521 * @since 9.0
522 */
523 double getOffset() {
524 return offset;
525 }
526
527 /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
528 * <p>
529 * CCSDS Unsegmented Time Code is defined in the blue book:
530 * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
531 * </p>
532 * <p>
533 * If the date to be parsed is formatted using version 3 of the standard
534 * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
535 * field introduced in version 4 of the standard is not used, then the
536 * {@code preambleField2} parameter can be set to 0.
537 * </p>
538 *
539 * <p>This method uses the {@link DataContext#getDefault() default data context} if
540 * the CCSDS epoch is used.
541 *
542 * @param preambleField1 first byte of the field specifying the format, often
543 * not transmitted in data interfaces, as it is constant for a given data interface
544 * @param preambleField2 second byte of the field specifying the format
545 * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
546 * interfaces, as it is constant for a given data interface (value ignored if presence
547 * not signaled in {@code preambleField1})
548 * @param timeField byte array containing the time code
549 * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
550 * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
551 * may be null in this case)
552 * @return an instance corresponding to the specified date
553 * @see #parseCCSDSUnsegmentedTimeCode(byte, byte, byte[], AbsoluteDate, AbsoluteDate)
554 */
555 @DefaultDataContext
556 public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(final byte preambleField1,
557 final byte preambleField2,
558 final byte[] timeField,
559 final AbsoluteDate agencyDefinedEpoch) {
560 return parseCCSDSUnsegmentedTimeCode(preambleField1, preambleField2, timeField,
561 agencyDefinedEpoch,
562 DataContext.getDefault().getTimeScales().getCcsdsEpoch());
563 }
564
565 /**
566 * Build an instance from a CCSDS Unsegmented Time Code (CUC).
567 * <p>
568 * CCSDS Unsegmented Time Code is defined in the blue book: CCSDS Time Code Format
569 * (CCSDS 301.0-B-4) published in November 2010
570 * </p>
571 * <p>
572 * If the date to be parsed is formatted using version 3 of the standard (CCSDS
573 * 301.0-B-3 published in 2002) or if the extension of the preamble field introduced
574 * in version 4 of the standard is not used, then the {@code preambleField2} parameter
575 * can be set to 0.
576 * </p>
577 *
578 * @param preambleField1 first byte of the field specifying the format, often not
579 * transmitted in data interfaces, as it is constant for a
580 * given data interface
581 * @param preambleField2 second byte of the field specifying the format (added in
582 * revision 4 of the CCSDS standard in 2010), often not
583 * transmitted in data interfaces, as it is constant for a
584 * given data interface (value ignored if presence not
585 * signaled in {@code preambleField1})
586 * @param timeField byte array containing the time code
587 * @param agencyDefinedEpoch reference epoch, ignored if the preamble field specifies
588 * the {@link #CCSDS_EPOCH CCSDS reference epoch} is used
589 * (and hence may be null in this case)
590 * @param ccsdsEpoch reference epoch, ignored if the preamble field specifies
591 * the agency epoch is used.
592 * @return an instance corresponding to the specified date
593 * @since 10.1
594 */
595 public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(
596 final byte preambleField1,
597 final byte preambleField2,
598 final byte[] timeField,
599 final AbsoluteDate agencyDefinedEpoch,
600 final AbsoluteDate ccsdsEpoch) {
601
602 // time code identification and reference epoch
603 final AbsoluteDate epoch;
604 switch (preambleField1 & 0x70) {
605 case 0x10:
606 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
607 epoch = ccsdsEpoch;
608 break;
609 case 0x20:
610 // the reference epoch is agency defined
611 if (agencyDefinedEpoch == null) {
612 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
613 }
614 epoch = agencyDefinedEpoch;
615 break;
616 default :
617 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
618 formatByte(preambleField1));
619 }
620
621 // time field lengths
622 int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
623 int fineTimeLength = preambleField1 & 0x03;
624
625 if ((preambleField1 & 0x80) != 0x0) {
626 // there is an additional octet in preamble field
627 coarseTimeLength += (preambleField2 & 0x60) >>> 5;
628 fineTimeLength += (preambleField2 & 0x1C) >>> 2;
629 }
630
631 if (timeField.length != coarseTimeLength + fineTimeLength) {
632 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
633 timeField.length, coarseTimeLength + fineTimeLength);
634 }
635
636 double seconds = 0;
637 for (int i = 0; i < coarseTimeLength; ++i) {
638 seconds = seconds * 256 + toUnsigned(timeField[i]);
639 }
640 double subseconds = 0;
641 for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
642 subseconds = (subseconds + toUnsigned(timeField[i])) / 256;
643 }
644
645 return new AbsoluteDate(epoch, seconds).shiftedBy(subseconds);
646
647 }
648
649 /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
650 * <p>
651 * CCSDS Day Segmented Time Code is defined in the blue book:
652 * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
653 * </p>
654 *
655 * <p>This method uses the {@link DataContext#getDefault() default data context}.
656 *
657 * @param preambleField field specifying the format, often not transmitted in
658 * data interfaces, as it is constant for a given data interface
659 * @param timeField byte array containing the time code
660 * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
661 * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
662 * may be null in this case)
663 * @return an instance corresponding to the specified date
664 * @see #parseCCSDSDaySegmentedTimeCode(byte, byte[], DateComponents, TimeScale)
665 */
666 @DefaultDataContext
667 public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(final byte preambleField, final byte[] timeField,
668 final DateComponents agencyDefinedEpoch) {
669 return parseCCSDSDaySegmentedTimeCode(preambleField, timeField,
670 agencyDefinedEpoch, DataContext.getDefault().getTimeScales().getUTC());
671 }
672
673 /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
674 * <p>
675 * CCSDS Day Segmented Time Code is defined in the blue book:
676 * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
677 * </p>
678 * @param preambleField field specifying the format, often not transmitted in
679 * data interfaces, as it is constant for a given data interface
680 * @param timeField byte array containing the time code
681 * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
682 * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
683 * may be null in this case)
684 * @param utc time scale used to compute date and time components.
685 * @return an instance corresponding to the specified date
686 * @since 10.1
687 */
688 public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(
689 final byte preambleField,
690 final byte[] timeField,
691 final DateComponents agencyDefinedEpoch,
692 final TimeScale utc) {
693
694 // time code identification
695 if ((preambleField & 0xF0) != 0x40) {
696 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
697 formatByte(preambleField));
698 }
699
700 // reference epoch
701 final DateComponents epoch;
702 if ((preambleField & 0x08) == 0x00) {
703 // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
704 epoch = DateComponents.CCSDS_EPOCH;
705 } else {
706 // the reference epoch is agency defined
707 if (agencyDefinedEpoch == null) {
708 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
709 }
710 epoch = agencyDefinedEpoch;
711 }
712
713 // time field lengths
714 final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
715 final int subMillisecondLength = (preambleField & 0x03) << 1;
716 if (subMillisecondLength == 6) {
717 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
718 formatByte(preambleField));
719 }
720 if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
721 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
722 timeField.length, daySegmentLength + 4 + subMillisecondLength);
723 }
724
725
726 int i = 0;
727 int day = 0;
728 while (i < daySegmentLength) {
729 day = day * 256 + toUnsigned(timeField[i++]);
730 }
731
732 long milliInDay = 0l;
733 while (i < daySegmentLength + 4) {
734 milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
735 }
736 final int milli = (int) (milliInDay % 1000l);
737 final int seconds = (int) ((milliInDay - milli) / 1000l);
738
739 double subMilli = 0;
740 double divisor = 1;
741 while (i < timeField.length) {
742 subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
743 divisor *= 1000;
744 }
745
746 final DateComponentsateComponents">DateComponents date = new DateComponents(epoch, day);
747 final TimeComponentsimeComponents">TimeComponents time = new TimeComponents(seconds);
748 return new AbsoluteDate(date, time, utc).shiftedBy(milli * 1.0e-3 + subMilli / divisor);
749
750 }
751
752 /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
753 * <p>
754 * CCSDS Calendar Segmented Time Code is defined in the blue book:
755 * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
756 * </p>
757 *
758 * <p>This method uses the {@link DataContext#getDefault() default data context}.
759 *
760 * @param preambleField field specifying the format, often not transmitted in
761 * data interfaces, as it is constant for a given data interface
762 * @param timeField byte array containing the time code
763 * @return an instance corresponding to the specified date
764 * @see #parseCCSDSCalendarSegmentedTimeCode(byte, byte[], TimeScale)
765 */
766 @DefaultDataContext
767 public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField) {
768 return parseCCSDSCalendarSegmentedTimeCode(preambleField, timeField,
769 DataContext.getDefault().getTimeScales().getUTC());
770 }
771
772 /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
773 * <p>
774 * CCSDS Calendar Segmented Time Code is defined in the blue book:
775 * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
776 * </p>
777 * @param preambleField field specifying the format, often not transmitted in
778 * data interfaces, as it is constant for a given data interface
779 * @param timeField byte array containing the time code
780 * @param utc time scale used to compute date and time components.
781 * @return an instance corresponding to the specified date
782 * @since 10.1
783 */
784 public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(
785 final byte preambleField,
786 final byte[] timeField,
787 final TimeScale utc) {
788
789 // time code identification
790 if ((preambleField & 0xF0) != 0x50) {
791 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
792 formatByte(preambleField));
793 }
794
795 // time field length
796 final int length = 7 + (preambleField & 0x07);
797 if (length == 14) {
798 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
799 formatByte(preambleField));
800 }
801 if (timeField.length != length) {
802 throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
803 timeField.length, length);
804 }
805
806 // date part in the first four bytes
807 final DateComponents date;
808 if ((preambleField & 0x08) == 0x00) {
809 // month of year and day of month variation
810 date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
811 toUnsigned(timeField[2]),
812 toUnsigned(timeField[3]));
813 } else {
814 // day of year variation
815 date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
816 toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
817 }
818
819 // time part from bytes 5 to last (between 7 and 13 depending on precision)
820 final TimeComponentsimeComponents">TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
821 toUnsigned(timeField[5]),
822 toUnsigned(timeField[6]));
823 double subSecond = 0;
824 double divisor = 1;
825 for (int i = 7; i < length; ++i) {
826 subSecond = subSecond * 100 + toUnsigned(timeField[i]);
827 divisor *= 100;
828 }
829
830 return new AbsoluteDate(date, time, utc).shiftedBy(subSecond / divisor);
831
832 }
833
834 /** Decode a signed byte as an unsigned int value.
835 * @param b byte to decode
836 * @return an unsigned int value
837 */
838 private static int toUnsigned(final byte b) {
839 final int i = (int) b;
840 return (i < 0) ? 256 + i : i;
841 }
842
843 /** Format a byte as an hex string for error messages.
844 * @param data byte to format
845 * @return a formatted string
846 */
847 private static String formatByte(final byte data) {
848 return "0x" + Integer.toHexString(data).toUpperCase();
849 }
850
851 /** Build an instance corresponding to a Julian Day date.
852 * @param jd Julian day
853 * @param secondsSinceNoon seconds in the Julian day
854 * (BEWARE, Julian days start at noon, so 0.0 is noon)
855 * @param timeScale time scale in which the seconds in day are defined
856 * @return a new instant
857 */
858 public static AbsoluteDate createJDDate(final int jd, final double secondsSinceNoon,
859 final TimeScale timeScale) {
860 return new AbsoluteDate(new DateComponents(DateComponents.JULIAN_EPOCH, jd),
861 TimeComponents.H12, timeScale).shiftedBy(secondsSinceNoon);
862 }
863
864 /** Build an instance corresponding to a Modified Julian Day date.
865 * @param mjd modified Julian day
866 * @param secondsInDay seconds in the day
867 * @param timeScale time scale in which the seconds in day are defined
868 * @return a new instant
869 * @exception OrekitIllegalArgumentException if seconds number is out of range
870 */
871 public static AbsoluteDate createMJDDate(final int mjd, final double secondsInDay,
872 final TimeScale timeScale)
873 throws OrekitIllegalArgumentException {
874 final DateComponents#DateComponents">DateComponents dc = new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd);
875 final TimeComponents tc;
876 if (secondsInDay >= Constants.JULIAN_DAY) {
877 // check we are really allowed to use this number of seconds
878 final int secondsA = 86399; // 23:59:59, i.e. 59s in the last minute of the day
879 final double secondsB = secondsInDay - secondsA;
880 final TimeComponentseComponents">TimeComponents safeTC = new TimeComponents(secondsA, 0.0);
881 final AbsoluteDateuteDate">AbsoluteDate safeDate = new AbsoluteDate(dc, safeTC, timeScale);
882 if (timeScale.minuteDuration(safeDate) > 59 + secondsB) {
883 // we are within the last minute of the day, the number of seconds is OK
884 return safeDate.shiftedBy(secondsB);
885 } else {
886 // let TimeComponents trigger an OrekitIllegalArgumentException
887 // for the wrong number of seconds
888 tc = new TimeComponents(secondsA, secondsB);
889 }
890 } else {
891 tc = new TimeComponents(secondsInDay);
892 }
893
894 // create the date
895 return new AbsoluteDate(dc, tc, timeScale);
896
897 }
898
899
900 /** Build an instance corresponding to a Julian Epoch (JE).
901 * <p>According to Lieske paper: <a
902 * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
903 * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
904 * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
905 * <pre>
906 * JE = 2000.0 + (JED - 2451545.0) / 365.25
907 * </pre>
908 * <p>
909 * This method reverts the formula above and computes an {@code AbsoluteDate} from the Julian Epoch.
910 * </p>
911 *
912 * <p>This method uses the {@link DataContext#getDefault() default data context}.
913 *
914 * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
915 * @return a new instant
916 * @see #J2000_EPOCH
917 * @see #createBesselianEpoch(double)
918 * @see TimeScales#createJulianEpoch(double)
919 */
920 @DefaultDataContext
921 public static AbsoluteDate createJulianEpoch(final double julianEpoch) {
922 return DataContext.getDefault().getTimeScales().createJulianEpoch(julianEpoch);
923 }
924
925 /** Build an instance corresponding to a Besselian Epoch (BE).
926 * <p>According to Lieske paper: <a
927 * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
928 * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
929 * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
930 * <pre>
931 * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
932 * </pre>
933 * <p>
934 * This method reverts the formula above and computes an {@code AbsoluteDate} from the Besselian Epoch.
935 * </p>
936 *
937 * <p>This method uses the {@link DataContext#getDefault() default data context}.
938 *
939 * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
940 * @return a new instant
941 * @see #createJulianEpoch(double)
942 * @see TimeScales#createBesselianEpoch(double)
943 */
944 @DefaultDataContext
945 public static AbsoluteDate createBesselianEpoch(final double besselianEpoch) {
946 return DataContext.getDefault().getTimeScales()
947 .createBesselianEpoch(besselianEpoch);
948 }
949
950 /** Get a time-shifted date.
951 * <p>
952 * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
953 * </p>
954 * @param dt time shift in seconds
955 * @return a new date, shifted with respect to instance (which is immutable)
956 * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
957 * @see org.orekit.attitudes.Attitude#shiftedBy(double)
958 * @see org.orekit.orbits.Orbit#shiftedBy(double)
959 * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
960 */
961 public AbsoluteDate shiftedBy(final double dt) {
962 return new AbsoluteDate(this, dt);
963 }
964
965 /** Compute the physically elapsed duration between two instants.
966 * <p>The returned duration is the number of seconds physically
967 * elapsed between the two instants, measured in a regular time
968 * scale with respect to surface of the Earth (i.e either the {@link
969 * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
970 * GPSScale GPS scale}). It is the only method that gives a
971 * duration with a physical meaning.</p>
972 * <p>This method gives the same result (with less computation)
973 * as calling {@link #offsetFrom(AbsoluteDate, TimeScale)}
974 * with a second argument set to one of the regular scales cited
975 * above.</p>
976 * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
977 * double)} constructor.</p>
978 * @param instant instant to subtract from the instance
979 * @return offset in seconds between the two instants (positive
980 * if the instance is posterior to the argument)
981 * @see #offsetFrom(AbsoluteDate, TimeScale)
982 * @see #AbsoluteDate(AbsoluteDate, double)
983 */
984 public double durationFrom(final AbsoluteDate instant) {
985 return (epoch - instant.epoch) + (offset - instant.offset);
986 }
987
988 /** Compute the apparent clock offset between two instant <em>in the
989 * perspective of a specific {@link TimeScale time scale}</em>.
990 * <p>The offset is the number of seconds counted in the given
991 * time scale between the locations of the two instants, with
992 * all time scale irregularities removed (i.e. considering all
993 * days are exactly 86400 seconds long). This method will give
994 * a result that may not have a physical meaning if the time scale
995 * is irregular. For example since a leap second was introduced at
996 * the end of 2005, the apparent offset between 2005-12-31T23:59:59
997 * and 2006-01-01T00:00:00 is 1 second, but the physical duration
998 * of the corresponding time interval as returned by the {@link
999 * #durationFrom(AbsoluteDate)} method is 2 seconds.</p>
1000 * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
1001 * double, TimeScale)} constructor.</p>
1002 * @param instant instant to subtract from the instance
1003 * @param timeScale time scale with respect to which the offset should
1004 * be computed
1005 * @return apparent clock offset in seconds between the two instants
1006 * (positive if the instance is posterior to the argument)
1007 * @see #durationFrom(AbsoluteDate)
1008 * @see #AbsoluteDate(AbsoluteDate, double, TimeScale)
1009 */
1010 public double offsetFrom(final AbsoluteDate instant, final TimeScale timeScale) {
1011 final long elapsedDurationA = epoch - instant.epoch;
1012 final double elapsedDurationB = (offset + timeScale.offsetFromTAI(this)) -
1013 (instant.offset + timeScale.offsetFromTAI(instant));
1014 return elapsedDurationA + elapsedDurationB;
1015 }
1016
1017 /** Compute the offset between two time scales at the current instant.
1018 * <p>The offset is defined as <i>l₁-l₂</i>
1019 * where <i>l₁</i> is the location of the instant in
1020 * the <code>scale1</code> time scale and <i>l₂</i> is the
1021 * location of the instant in the <code>scale2</code> time scale.</p>
1022 * @param scale1 first time scale
1023 * @param scale2 second time scale
1024 * @return offset in seconds between the two time scales at the
1025 * current instant
1026 */
1027 public double timeScalesOffset(final TimeScaleScale">TimeScale scale1, final TimeScale scale2) {
1028 return scale1.offsetFromTAI(this) - scale2.offsetFromTAI(this);
1029 }
1030
1031 /** Convert the instance to a Java {@link java.util.Date Date}.
1032 * <p>Conversion to the Date class induces a loss of precision because
1033 * the Date class does not provide sub-millisecond information. Java Dates
1034 * are considered to be locations in some times scales.</p>
1035 * @param timeScale time scale to use
1036 * @return a {@link java.util.Date Date} instance representing the location
1037 * of the instant in the time scale
1038 */
1039 public Date toDate(final TimeScale timeScale) {
1040 final double time = epoch + (offset + timeScale.offsetFromTAI(this));
1041 return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
1042 }
1043
1044 /** Split the instance into date/time components.
1045 * @param timeScale time scale to use
1046 * @return date/time components
1047 */
1048 public DateTimeComponents getComponents(final TimeScale timeScale) {
1049
1050 if (Double.isInfinite(offset)) {
1051 // special handling for past and future infinity
1052 if (offset < 0) {
1053 return new DateTimeComponents(DateComponents.MIN_EPOCH, TimeComponents.H00);
1054 } else {
1055 return new DateTimeComponents(DateComponents.MAX_EPOCH,
1056 new TimeComponents(23, 59, 59.999));
1057 }
1058 }
1059
1060 // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
1061 // using Møller-Knuth TwoSum algorithm without branching
1062 // the following statements must NOT be simplified, they rely on floating point
1063 // arithmetic properties (rounding and representable numbers)
1064 // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
1065 // is sum + residual, where sum is the closest representable number to the exact
1066 // result and residual is the missing part that does not fit in the first number
1067 final double taiOffset = timeScale.offsetFromTAI(this);
1068 final double sum = offset + taiOffset;
1069 final double oPrime = sum - taiOffset;
1070 final double dPrime = sum - oPrime;
1071 final double deltaO = offset - oPrime;
1072 final double deltaD = taiOffset - dPrime;
1073 final double residual = deltaO + deltaD;
1074
1075 // split date and time
1076 final long carry = (long) FastMath.floor(sum);
1077 double offset2000B = (sum - carry) + residual;
1078 long offset2000A = epoch + carry + 43200l;
1079 if (offset2000B < 0) {
1080 offset2000A -= 1;
1081 offset2000B += 1;
1082 }
1083 long time = offset2000A % 86400l;
1084 if (time < 0l) {
1085 time += 86400l;
1086 }
1087 final int date = (int) ((offset2000A - time) / 86400l);
1088
1089 // extract calendar elements
1090 final DateComponentsnts">DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
1091
1092 // extract time element, accounting for leap seconds
1093 final double leap = timeScale.insideLeap(this) ? timeScale.getLeap(this) : 0;
1094 final int minuteDuration = timeScale.minuteDuration(this);
1095 final TimeComponents timeComponents =
1096 TimeComponents.fromSeconds((int) time, offset2000B, leap, minuteDuration);
1097
1098 // build the components
1099 return new DateTimeComponents(dateComponents, timeComponents);
1100
1101 }
1102
1103 /** Split the instance into date/time components for a local time.
1104 *
1105 * <p>This method uses the {@link DataContext#getDefault() default data context}.
1106 *
1107 * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
1108 * negative Westward UTC)
1109 * @return date/time components
1110 * @since 7.2
1111 * @see #getComponents(int, TimeScale)
1112 */
1113 @DefaultDataContext
1114 public DateTimeComponents getComponents(final int minutesFromUTC) {
1115 return getComponents(minutesFromUTC,
1116 DataContext.getDefault().getTimeScales().getUTC());
1117 }
1118
1119 /**
1120 * Split the instance into date/time components for a local time.
1121 *
1122 * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
1123 * negative Westward UTC)
1124 * @param utc time scale used to compute date and time components.
1125 * @return date/time components
1126 * @since 10.1
1127 */
1128 public DateTimeComponents getComponents(final int minutesFromUTC,
1129 final TimeScale utc) {
1130
1131 final DateTimeComponents utcComponents = getComponents(utc);
1132
1133 // shift the date according to UTC offset, but WITHOUT touching the seconds,
1134 // as they may exceed 60.0 during a leap seconds introduction,
1135 // and we want to preserve these special cases
1136 final double seconds = utcComponents.getTime().getSecond();
1137
1138 int minute = utcComponents.getTime().getMinute() + minutesFromUTC;
1139 final int hourShift;
1140 if (minute < 0) {
1141 hourShift = (minute - 59) / 60;
1142 } else if (minute > 59) {
1143 hourShift = minute / 60;
1144 } else {
1145 hourShift = 0;
1146 }
1147 minute -= 60 * hourShift;
1148
1149 int hour = utcComponents.getTime().getHour() + hourShift;
1150 final int dayShift;
1151 if (hour < 0) {
1152 dayShift = (hour - 23) / 24;
1153 } else if (hour > 23) {
1154 dayShift = hour / 24;
1155 } else {
1156 dayShift = 0;
1157 }
1158 hour -= 24 * dayShift;
1159
1160 return new DateTimeComponents(new DateComponents(utcComponents.getDate(), dayShift),
1161 new TimeComponents(hour, minute, seconds, minutesFromUTC));
1162
1163 }
1164
1165 /** Split the instance into date/time components for a time zone.
1166 *
1167 * <p>This method uses the {@link DataContext#getDefault() default data context}.
1168 *
1169 * @param timeZone time zone
1170 * @return date/time components
1171 * @since 7.2
1172 * @see #getComponents(TimeZone, TimeScale)
1173 */
1174 @DefaultDataContext
1175 public DateTimeComponents getComponents(final TimeZone timeZone) {
1176 return getComponents(timeZone, DataContext.getDefault().getTimeScales().getUTC());
1177 }
1178
1179 /**
1180 * Split the instance into date/time components for a time zone.
1181 *
1182 * @param timeZone time zone
1183 * @param utc time scale used to computed date and time components.
1184 * @return date/time components
1185 * @since 10.1
1186 */
1187 public DateTimeComponents getComponents(final TimeZone timeZone,
1188 final TimeScale utc) {
1189 final AbsoluteDateteDate">AbsoluteDate javaEpoch = new AbsoluteDate(DateComponents.JAVA_EPOCH, utc);
1190 final long milliseconds = FastMath.round(1000 * offsetFrom(javaEpoch, utc));
1191 return getComponents(timeZone.getOffset(milliseconds) / 60000, utc);
1192 }
1193
1194 /** Compare the instance with another date.
1195 * @param date other date to compare the instance to
1196 * @return a negative integer, zero, or a positive integer as this date
1197 * is before, simultaneous, or after the specified date.
1198 */
1199 public int compareTo(final AbsoluteDate date) {
1200 final double duration = durationFrom(date);
1201 if (!Double.isNaN(duration)) {
1202 return Double.compare(duration, 0.0);
1203 }
1204 // both dates are infinity or one is NaN or both are NaN
1205 return Double.compare(offset, date.offset);
1206 }
1207
1208 /** {@inheritDoc} */
1209 public AbsoluteDate getDate() {
1210 return this;
1211 }
1212
1213 /** Check if the instance represents the same time as another instance.
1214 * @param date other date
1215 * @return true if the instance and the other date refer to the same instant
1216 */
1217 public boolean equals(final Object date) {
1218
1219 if (date == this) {
1220 // first fast check
1221 return true;
1222 }
1223
1224 if ((date != null) && (date instanceof AbsoluteDate)) {
1225 return durationFrom((AbsoluteDate) date) == 0;
1226 }
1227
1228 return false;
1229
1230 }
1231
1232 /** Check if the instance represents the same time as another.
1233 * @param other the instant to compare this date to
1234 * @return true if the instance and the argument refer to the same instant
1235 * @see #isCloseTo(TimeStamped, double)
1236 * @since 10.1
1237 */
1238 public boolean isEqualTo(final TimeStamped other) {
1239 return this.equals(other.getDate());
1240 }
1241
1242 /** Check if the instance time is close to another.
1243 * @param other the instant to compare this date to
1244 * @param tolerance the separation, in seconds, under which the two instants will be considered close to each other
1245 * @return true if the duration between the instance and the argument is strictly below the tolerance
1246 * @see #isEqualTo(TimeStamped)
1247 * @since 10.1
1248 */
1249 public boolean isCloseTo(final TimeStamped other, final double tolerance) {
1250 return FastMath.abs(this.durationFrom(other.getDate())) < tolerance;
1251 }
1252
1253 /** Check if the instance represents a time that is strictly before another.
1254 * @param other the instant to compare this date to
1255 * @return true if the instance is strictly before the argument when ordering chronologically
1256 * @see #isBeforeOrEqualTo(TimeStamped)
1257 * @since 10.1
1258 */
1259 public boolean isBefore(final TimeStamped other) {
1260 return this.compareTo(other.getDate()) < 0;
1261 }
1262
1263 /** Check if the instance represents a time that is strictly after another.
1264 * @param other the instant to compare this date to
1265 * @return true if the instance is strictly after the argument when ordering chronologically
1266 * @see #isAfterOrEqualTo(TimeStamped)
1267 * @since 10.1
1268 */
1269 public boolean isAfter(final TimeStamped other) {
1270 return this.compareTo(other.getDate()) > 0;
1271 }
1272
1273 /** Check if the instance represents a time that is before or equal to another.
1274 * @param other the instant to compare this date to
1275 * @return true if the instance is before (or equal to) the argument when ordering chronologically
1276 * @see #isBefore(TimeStamped)
1277 * @since 10.1
1278 */
1279 public boolean isBeforeOrEqualTo(final TimeStamped other) {
1280 return this.isEqualTo(other) || this.isBefore(other);
1281 }
1282
1283 /** Check if the instance represents a time that is after or equal to another.
1284 * @param other the instant to compare this date to
1285 * @return true if the instance is after (or equal to) the argument when ordering chronologically
1286 * @see #isAfterOrEqualTo(TimeStamped)
1287 * @since 10.1
1288 */
1289 public boolean isAfterOrEqualTo(final TimeStamped other) {
1290 return this.isEqualTo(other) || this.isAfter(other);
1291 }
1292
1293 /** Check if the instance represents a time that is strictly between two others representing
1294 * the boundaries of a time span. The two boundaries can be provided in any order: in other words,
1295 * whether <code>boundary</code> represents a time that is before or after <code>otherBoundary</code> will
1296 * not change the result of this method.
1297 * @param boundary one end of the time span
1298 * @param otherBoundary the other end of the time span
1299 * @return true if the instance is strictly between the two arguments when ordering chronologically
1300 * @see #isBetweenOrEqualTo(TimeStamped, TimeStamped)
1301 * @since 10.1
1302 */
1303 public boolean isBetween(final TimeStampedamped">TimeStamped boundary, final TimeStamped otherBoundary) {
1304 final TimeStamped beginning;
1305 final TimeStamped end;
1306 if (boundary.getDate().isBefore(otherBoundary)) {
1307 beginning = boundary;
1308 end = otherBoundary;
1309 } else {
1310 beginning = otherBoundary;
1311 end = boundary;
1312 }
1313 return this.isAfter(beginning) && this.isBefore(end);
1314 }
1315
1316 /** Check if the instance represents a time that is between two others representing
1317 * the boundaries of a time span, or equal to one of them. The two boundaries can be provided in any order:
1318 * in other words, whether <code>boundary</code> represents a time that is before or after
1319 * <code>otherBoundary</code> will not change the result of this method.
1320 * @param boundary one end of the time span
1321 * @param otherBoundary the other end of the time span
1322 * @return true if the instance is between the two arguments (or equal to at least one of them)
1323 * when ordering chronologically
1324 * @see #isBetween(TimeStamped, TimeStamped)
1325 * @since 10.1
1326 */
1327 public boolean isBetweenOrEqualTo(final TimeStampedamped">TimeStamped boundary, final TimeStamped otherBoundary) {
1328 return this.isEqualTo(boundary) || this.isEqualTo(otherBoundary) || this.isBetween(boundary, otherBoundary);
1329 }
1330
1331 /** Get a hashcode for this date.
1332 * @return hashcode
1333 */
1334 public int hashCode() {
1335 final long l = Double.doubleToLongBits(durationFrom(ARBITRARY_EPOCH));
1336 return (int) (l ^ (l >>> 32));
1337 }
1338
1339 /** Get a String representation of the instant location in UTC time scale.
1340 *
1341 * <p>This method uses the {@link DataContext#getDefault() default data context}.
1342 *
1343 * @return a string representation of the instance,
1344 * in ISO-8601 format with milliseconds accuracy
1345 * @see #toString(TimeScale)
1346 */
1347 @DefaultDataContext
1348 public String toString() {
1349 return toString(DataContext.getDefault().getTimeScales().getUTC());
1350 }
1351
1352 /** Get a String representation of the instant location.
1353 * @param timeScale time scale to use
1354 * @return a string representation of the instance,
1355 * in ISO-8601 format with milliseconds accuracy
1356 */
1357 public String toString(final TimeScale timeScale) {
1358 return getComponents(timeScale).toString(timeScale.minuteDuration(this));
1359 }
1360
1361 /** Get a String representation of the instant location for a local time.
1362 *
1363 * <p>This method uses the {@link DataContext#getDefault() default data context}.
1364 *
1365 * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
1366 * negative Westward UTC).
1367 * @return string representation of the instance,
1368 * in ISO-8601 format with milliseconds accuracy
1369 * @since 7.2
1370 * @see #toString(int, TimeScale)
1371 */
1372 @DefaultDataContext
1373 public String toString(final int minutesFromUTC) {
1374 return toString(minutesFromUTC,
1375 DataContext.getDefault().getTimeScales().getUTC());
1376 }
1377
1378 /**
1379 * Get a String representation of the instant location for a local time.
1380 *
1381 * @param minutesFromUTC offset in <em>minutes</em> from UTC (positive Eastwards UTC,
1382 * negative Westward UTC).
1383 * @param utc time scale used to compute date and time components.
1384 * @return string representation of the instance, in ISO-8601 format with milliseconds
1385 * accuracy
1386 * @since 10.1
1387 */
1388 public String toString(final int minutesFromUTC, final TimeScale utc) {
1389 final int minuteDuration = utc.minuteDuration(this);
1390 return getComponents(minutesFromUTC, utc).toString(minuteDuration);
1391 }
1392
1393 /** Get a String representation of the instant location for a time zone.
1394 *
1395 * <p>This method uses the {@link DataContext#getDefault() default data context}.
1396 *
1397 * @param timeZone time zone
1398 * @return string representation of the instance,
1399 * in ISO-8601 format with milliseconds accuracy
1400 * @since 7.2
1401 * @see #toString(TimeZone, TimeScale)
1402 */
1403 @DefaultDataContext
1404 public String toString(final TimeZone timeZone) {
1405 return toString(timeZone, DataContext.getDefault().getTimeScales().getUTC());
1406 }
1407
1408 /**
1409 * Get a String representation of the instant location for a time zone.
1410 *
1411 * @param timeZone time zone
1412 * @param utc time scale used to compute date and time components.
1413 * @return string representation of the instance, in ISO-8601 format with milliseconds
1414 * accuracy
1415 * @since 10.1
1416 */
1417 public String toString(final TimeZone timeZone, final TimeScale utc) {
1418 final int minuteDuration = utc.minuteDuration(this);
1419 return getComponents(timeZone, utc).toString(minuteDuration);
1420 }
1421
1422 /**
1423 * Represent the given date as a string according to the format in RFC 3339. RFC3339
1424 * is a restricted subset of ISO 8601 with a well defined grammar.
1425 *
1426 * <p>This method is different than {@link AbsoluteDate#toString(TimeScale)} in that
1427 * it includes a {@code "Z"} at the end to indicate the time zone and enough precision
1428 * to represent the point in time without rounding up to the next minute.
1429 *
1430 * <p>RFC3339 is unable to represent BC years, years of 10000 or more, time zone
1431 * offsets of 100 hours or more, or NaN. In these cases the value returned from this
1432 * method will not be valid RFC3339 format.
1433 *
1434 * @param utc time scale.
1435 * @return RFC 3339 format string.
1436 * @see <a href="https://tools.ietf.org/html/rfc3339#page-8">RFC 3339</a>
1437 * @see DateTimeComponents#toStringRfc3339()
1438 * @see #toString(TimeScale)
1439 * @see #getComponents(TimeScale)
1440 */
1441 public String toStringRfc3339(final TimeScale utc) {
1442 return this.getComponents(utc).toStringRfc3339();
1443 }
1444
1445 }