/
JulianDate.js
1232 lines (1116 loc) · 40.3 KB
/
JulianDate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sprintf from "../ThirdParty/sprintf.js";
import binarySearch from "./binarySearch.js";
import defaultValue from "./defaultValue.js";
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";
import GregorianDate from "./GregorianDate.js";
import isLeapYear from "./isLeapYear.js";
import LeapSecond from "./LeapSecond.js";
import TimeConstants from "./TimeConstants.js";
import TimeStandard from "./TimeStandard.js";
var gregorianDateScratch = new GregorianDate();
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var daysInLeapFeburary = 29;
function compareLeapSecondDates(leapSecond, dateToFind) {
return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
}
// we don't really need a leap second instance, anything with a julianDate property will do
var binarySearchScratchLeapSecond = new LeapSecond();
function convertUtcToTai(julianDate) {
//Even though julianDate is in UTC, we'll treat it as TAI and
//search the leap second table for it.
binarySearchScratchLeapSecond.julianDate = julianDate;
var leapSeconds = JulianDate.leapSeconds;
var index = binarySearch(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates
);
if (index < 0) {
index = ~index;
}
if (index >= leapSeconds.length) {
index = leapSeconds.length - 1;
}
var offset = leapSeconds[index].offset;
if (index > 0) {
//Now we have the index of the closest leap second that comes on or after our UTC time.
//However, if the difference between the UTC date being converted and the TAI
//defined leap second is greater than the offset, we are off by one and need to use
//the previous leap second.
var difference = JulianDate.secondsDifference(
leapSeconds[index].julianDate,
julianDate
);
if (difference > offset) {
index--;
offset = leapSeconds[index].offset;
}
}
JulianDate.addSeconds(julianDate, offset, julianDate);
}
function convertTaiToUtc(julianDate, result) {
binarySearchScratchLeapSecond.julianDate = julianDate;
var leapSeconds = JulianDate.leapSeconds;
var index = binarySearch(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates
);
if (index < 0) {
index = ~index;
}
//All times before our first leap second get the first offset.
if (index === 0) {
return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
}
//All times after our leap second get the last offset.
if (index >= leapSeconds.length) {
return JulianDate.addSeconds(
julianDate,
-leapSeconds[index - 1].offset,
result
);
}
//Compute the difference between the found leap second and the time we are converting.
var difference = JulianDate.secondsDifference(
leapSeconds[index].julianDate,
julianDate
);
if (difference === 0) {
//The date is in our leap second table.
return JulianDate.addSeconds(
julianDate,
-leapSeconds[index].offset,
result
);
}
if (difference <= 1.0) {
//The requested date is during the moment of a leap second, then we cannot convert to UTC
return undefined;
}
//The time is in between two leap seconds, index is the leap second after the date
//we're converting, so we subtract one to get the correct LeapSecond instance.
return JulianDate.addSeconds(
julianDate,
-leapSeconds[--index].offset,
result
);
}
function setComponents(wholeDays, secondsOfDay, julianDate) {
var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
wholeDays += extraDays;
secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
if (secondsOfDay < 0) {
wholeDays--;
secondsOfDay += TimeConstants.SECONDS_PER_DAY;
}
julianDate.dayNumber = wholeDays;
julianDate.secondsOfDay = secondsOfDay;
return julianDate;
}
function computeJulianDateComponents(
year,
month,
day,
hour,
minute,
second,
millisecond
) {
// Algorithm from page 604 of the Explanatory Supplement to the
// Astronomical Almanac (Seidelmann 1992).
var a = ((month - 14) / 12) | 0;
var b = year + 4800 + a;
var dayNumber =
(((1461 * b) / 4) | 0) +
(((367 * (month - 2 - 12 * a)) / 12) | 0) -
(((3 * (((b + 100) / 100) | 0)) / 4) | 0) +
day -
32075;
// JulianDates are noon-based
hour = hour - 12;
if (hour < 0) {
hour += 24;
}
var secondsOfDay =
second +
(hour * TimeConstants.SECONDS_PER_HOUR +
minute * TimeConstants.SECONDS_PER_MINUTE +
millisecond * TimeConstants.SECONDS_PER_MILLISECOND);
if (secondsOfDay >= 43200.0) {
dayNumber -= 1;
}
return [dayNumber, secondsOfDay];
}
//Regular expressions used for ISO8601 date parsing.
//YYYY
var matchCalendarYear = /^(\d{4})$/;
//YYYY-MM (YYYYMM is invalid)
var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
//YYYY-DDD or YYYYDDD
var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
//YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
//YYYY-MM-DD or YYYYMMDD
var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
// Match utc offset
var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
// Match hours HH or HH.xxxxx
var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
// Match hours/minutes HH:MM HHMM.xxxxx
var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
// Match hours/minutes HH:MM:SS HHMMSS.xxxxx
var matchHoursMinutesSeconds =
/^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
var iso8601ErrorMessage = "Invalid ISO 8601 date.";
/**
* Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
* For increased precision, this class stores the whole number part of the date and the seconds
* part of the date in separate components. In order to be safe for arithmetic and represent
* leap seconds, the date is always stored in the International Atomic Time standard
* {@link TimeStandard.TAI}.
* @alias JulianDate
* @constructor
*
* @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
* @param {Number} [secondsOfDay=0.0] The number of seconds into the current Julian Day Number. Fractional seconds, negative seconds and seconds greater than a day will be handled correctly.
* @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
*/
function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
/**
* Gets or sets the number of whole days.
* @type {Number}
*/
this.dayNumber = undefined;
/**
* Gets or sets the number of seconds into the current day.
* @type {Number}
*/
this.secondsOfDay = undefined;
julianDayNumber = defaultValue(julianDayNumber, 0.0);
secondsOfDay = defaultValue(secondsOfDay, 0.0);
timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
//If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
var wholeDays = julianDayNumber | 0;
secondsOfDay =
secondsOfDay +
(julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
setComponents(wholeDays, secondsOfDay, this);
if (timeStandard === TimeStandard.UTC) {
convertUtcToTai(this);
}
}
/**
* Creates a new instance from a GregorianDate.
*
* @param {GregorianDate} date A GregorianDate.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} date must be a valid GregorianDate.
*/
JulianDate.fromGregorianDate = function (date, result) {
//>>includeStart('debug', pragmas.debug);
if (!(date instanceof GregorianDate)) {
throw new DeveloperError("date must be a valid GregorianDate.");
}
//>>includeEnd('debug');
var components = computeJulianDateComponents(
date.year,
date.month,
date.day,
date.hour,
date.minute,
date.second,
date.millisecond
);
if (!defined(result)) {
return new JulianDate(components[0], components[1], TimeStandard.UTC);
}
setComponents(components[0], components[1], result);
convertUtcToTai(result);
return result;
};
/**
* Creates a new instance from a JavaScript Date.
*
* @param {Date} date A JavaScript Date.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} date must be a valid JavaScript Date.
*/
JulianDate.fromDate = function (date, result) {
//>>includeStart('debug', pragmas.debug);
if (!(date instanceof Date) || isNaN(date.getTime())) {
throw new DeveloperError("date must be a valid JavaScript Date.");
}
//>>includeEnd('debug');
var components = computeJulianDateComponents(
date.getUTCFullYear(),
date.getUTCMonth() + 1,
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds()
);
if (!defined(result)) {
return new JulianDate(components[0], components[1], TimeStandard.UTC);
}
setComponents(components[0], components[1], result);
convertUtcToTai(result);
return result;
};
/**
* Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
* This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
* specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
*
* @param {String} iso8601String An ISO 8601 date.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} Invalid ISO 8601 date.
*/
JulianDate.fromIso8601 = function (iso8601String, result) {
//>>includeStart('debug', pragmas.debug);
if (typeof iso8601String !== "string") {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug');
//Comma and decimal point both indicate a fractional number according to ISO 8601,
//start out by blanket replacing , with . which is the only valid such symbol in JS.
iso8601String = iso8601String.replace(",", ".");
//Split the string into its date and time components, denoted by a mandatory T
var tokens = iso8601String.split("T");
var year;
var month = 1;
var day = 1;
var hour = 0;
var minute = 0;
var second = 0;
var millisecond = 0;
//Lacking a time is okay, but a missing date is illegal.
var date = tokens[0];
var time = tokens[1];
var tmp;
var inLeapYear;
//>>includeStart('debug', pragmas.debug);
if (!defined(date)) {
throw new DeveloperError(iso8601ErrorMessage);
}
var dashCount;
//>>includeEnd('debug');
//First match the date against possible regular expressions.
tokens = date.match(matchCalendarDate);
if (tokens !== null) {
//>>includeStart('debug', pragmas.debug);
dashCount = date.split("-").length - 1;
if (dashCount > 0 && dashCount !== 2) {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug');
year = +tokens[1];
month = +tokens[2];
day = +tokens[3];
} else {
tokens = date.match(matchCalendarMonth);
if (tokens !== null) {
year = +tokens[1];
month = +tokens[2];
} else {
tokens = date.match(matchCalendarYear);
if (tokens !== null) {
year = +tokens[1];
} else {
//Not a year/month/day so it must be an ordinal date.
var dayOfYear;
tokens = date.match(matchOrdinalDate);
if (tokens !== null) {
year = +tokens[1];
dayOfYear = +tokens[2];
inLeapYear = isLeapYear(year);
//This validation is only applicable for this format.
//>>includeStart('debug', pragmas.debug);
if (
dayOfYear < 1 ||
(inLeapYear && dayOfYear > 366) ||
(!inLeapYear && dayOfYear > 365)
) {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
} else {
tokens = date.match(matchWeekDate);
if (tokens !== null) {
//ISO week date to ordinal date from
//http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
year = +tokens[1];
var weekNumber = +tokens[2];
var dayOfWeek = +tokens[3] || 0;
//>>includeStart('debug', pragmas.debug);
dashCount = date.split("-").length - 1;
if (
dashCount > 0 &&
((!defined(tokens[3]) && dashCount !== 1) ||
(defined(tokens[3]) && dashCount !== 2))
) {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
var january4 = new Date(Date.UTC(year, 0, 4));
dayOfYear = weekNumber * 7 + dayOfWeek - january4.getUTCDay() - 3;
} else {
//None of our regular expressions succeeded in parsing the date properly.
//>>includeStart('debug', pragmas.debug);
throw new DeveloperError(iso8601ErrorMessage);
//>>includeEnd('debug')
}
}
//Split an ordinal date into month/day.
tmp = new Date(Date.UTC(year, 0, 1));
tmp.setUTCDate(dayOfYear);
month = tmp.getUTCMonth() + 1;
day = tmp.getUTCDate();
}
}
}
//Now that we have all of the date components, validate them to make sure nothing is out of range.
inLeapYear = isLeapYear(year);
//>>includeStart('debug', pragmas.debug);
if (
month < 1 ||
month > 12 ||
day < 1 ||
((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) ||
(inLeapYear && month === 2 && day > daysInLeapFeburary)
) {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
//Now move onto the time string, which is much simpler.
//If no time is specified, it is considered the beginning of the day, UTC to match Javascript's implementation.
var offsetIndex;
if (defined(time)) {
tokens = time.match(matchHoursMinutesSeconds);
if (tokens !== null) {
//>>includeStart('debug', pragmas.debug);
dashCount = time.split(":").length - 1;
if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
hour = +tokens[1];
minute = +tokens[2];
second = +tokens[3];
millisecond = +(tokens[4] || 0) * 1000.0;
offsetIndex = 5;
} else {
tokens = time.match(matchHoursMinutes);
if (tokens !== null) {
//>>includeStart('debug', pragmas.debug);
dashCount = time.split(":").length - 1;
if (dashCount > 2) {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
hour = +tokens[1];
minute = +tokens[2];
second = +(tokens[3] || 0) * 60.0;
offsetIndex = 4;
} else {
tokens = time.match(matchHours);
if (tokens !== null) {
hour = +tokens[1];
minute = +(tokens[2] || 0) * 60.0;
offsetIndex = 3;
} else {
//>>includeStart('debug', pragmas.debug);
throw new DeveloperError(iso8601ErrorMessage);
//>>includeEnd('debug')
}
}
}
//Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
//>>includeStart('debug', pragmas.debug);
if (
minute >= 60 ||
second >= 61 ||
hour > 24 ||
(hour === 24 && (minute > 0 || second > 0 || millisecond > 0))
) {
throw new DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug');
//Check the UTC offset value, if no value exists, use local time
//a Z indicates UTC, + or - are offsets.
var offset = tokens[offsetIndex];
var offsetHours = +tokens[offsetIndex + 1];
var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
switch (offset) {
case "+":
hour = hour - offsetHours;
minute = minute - offsetMinutes;
break;
case "-":
hour = hour + offsetHours;
minute = minute + offsetMinutes;
break;
case "Z":
break;
default:
minute =
minute +
new Date(
Date.UTC(year, month - 1, day, hour, minute)
).getTimezoneOffset();
break;
}
}
//ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
//If that's the case, we need to temporarily subtract a second in order to build a UTC date.
//Then we add it back in after converting to TAI.
var isLeapSecond = second === 60;
if (isLeapSecond) {
second--;
}
//Even if we successfully parsed the string into its components, after applying UTC offset or
//special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
//milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
while (minute >= 60) {
minute -= 60;
hour++;
}
while (hour >= 24) {
hour -= 24;
day++;
}
tmp = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
while (day > tmp) {
day -= tmp;
month++;
if (month > 12) {
month -= 12;
year++;
}
tmp =
inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
}
//If UTC offset is at the beginning/end of the day, minutes can be negative.
while (minute < 0) {
minute += 60;
hour--;
}
while (hour < 0) {
hour += 24;
day--;
}
while (day < 1) {
month--;
if (month < 1) {
month += 12;
year--;
}
tmp =
inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
day += tmp;
}
//Now create the JulianDate components from the Gregorian date and actually create our instance.
var components = computeJulianDateComponents(
year,
month,
day,
hour,
minute,
second,
millisecond
);
if (!defined(result)) {
result = new JulianDate(components[0], components[1], TimeStandard.UTC);
} else {
setComponents(components[0], components[1], result);
convertUtcToTai(result);
}
//If we were on a leap second, add it back.
if (isLeapSecond) {
JulianDate.addSeconds(result, 1, result);
}
return result;
};
/**
* Creates a new instance that represents the current system time.
* This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
*
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*/
JulianDate.now = function (result) {
return JulianDate.fromDate(new Date(), result);
};
var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
/**
* Creates a {@link GregorianDate} from the provided instance.
*
* @param {JulianDate} julianDate The date to be converted.
* @param {GregorianDate} [result] An existing instance to use for the result.
* @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
*/
JulianDate.toGregorianDate = function (julianDate, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(julianDate)) {
throw new DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
var isLeapSecond = false;
var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
if (!defined(thisUtc)) {
//Conversion to UTC will fail if we are during a leap second.
//If that's the case, subtract a second and convert again.
//JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
isLeapSecond = true;
}
var julianDayNumber = thisUtc.dayNumber;
var secondsOfDay = thisUtc.secondsOfDay;
if (secondsOfDay >= 43200.0) {
julianDayNumber += 1;
}
// Algorithm from page 604 of the Explanatory Supplement to the
// Astronomical Almanac (Seidelmann 1992).
var L = (julianDayNumber + 68569) | 0;
var N = ((4 * L) / 146097) | 0;
L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
var I = ((4000 * (L + 1)) / 1461001) | 0;
L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
var J = ((80 * L) / 2447) | 0;
var day = (L - (((2447 * J) / 80) | 0)) | 0;
L = (J / 11) | 0;
var month = (J + 2 - 12 * L) | 0;
var year = (100 * (N - 49) + I + L) | 0;
var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
var remainingSeconds = secondsOfDay - hour * TimeConstants.SECONDS_PER_HOUR;
var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
remainingSeconds =
remainingSeconds - minute * TimeConstants.SECONDS_PER_MINUTE;
var second = remainingSeconds | 0;
var millisecond =
(remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND;
// JulianDates are noon-based
hour += 12;
if (hour > 23) {
hour -= 24;
}
//If we were on a leap second, add it back.
if (isLeapSecond) {
second += 1;
}
if (!defined(result)) {
return new GregorianDate(
year,
month,
day,
hour,
minute,
second,
millisecond,
isLeapSecond
);
}
result.year = year;
result.month = month;
result.day = day;
result.hour = hour;
result.minute = minute;
result.second = second;
result.millisecond = millisecond;
result.isLeapSecond = isLeapSecond;
return result;
};
/**
* Creates a JavaScript Date from the provided instance.
* Since JavaScript dates are only accurate to the nearest millisecond and
* cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
* If the provided JulianDate is during a leap second, the previous second is used.
*
* @param {JulianDate} julianDate The date to be converted.
* @returns {Date} A new instance representing the provided date.
*/
JulianDate.toDate = function (julianDate) {
//>>includeStart('debug', pragmas.debug);
if (!defined(julianDate)) {
throw new DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
var second = gDate.second;
if (gDate.isLeapSecond) {
second -= 1;
}
return new Date(
Date.UTC(
gDate.year,
gDate.month - 1,
gDate.day,
gDate.hour,
gDate.minute,
second,
gDate.millisecond
)
);
};
/**
* Creates an ISO8601 representation of the provided date.
*
* @param {JulianDate} julianDate The date to be converted.
* @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
* @returns {String} The ISO8601 representation of the provided date.
*/
JulianDate.toIso8601 = function (julianDate, precision) {
//>>includeStart('debug', pragmas.debug);
if (!defined(julianDate)) {
throw new DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
var year = gDate.year;
var month = gDate.month;
var day = gDate.day;
var hour = gDate.hour;
var minute = gDate.minute;
var second = gDate.second;
var millisecond = gDate.millisecond;
// special case - Iso8601.MAXIMUM_VALUE produces a string which we can't parse unless we adjust.
// 10000-01-01T00:00:00 is the same instant as 9999-12-31T24:00:00
if (
year === 10000 &&
month === 1 &&
day === 1 &&
hour === 0 &&
minute === 0 &&
second === 0 &&
millisecond === 0
) {
year = 9999;
month = 12;
day = 31;
hour = 24;
}
var millisecondStr;
if (!defined(precision) && millisecond !== 0) {
//Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
millisecondStr = (millisecond * 0.01).toString().replace(".", "");
return sprintf(
"%04d-%02d-%02dT%02d:%02d:%02d.%sZ",
year,
month,
day,
hour,
minute,
second,
millisecondStr
);
}
//Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
if (!defined(precision) || precision === 0) {
return sprintf(
"%04d-%02d-%02dT%02d:%02d:%02dZ",
year,
month,
day,
hour,
minute,
second
);
}
//Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
millisecondStr = (millisecond * 0.01)
.toFixed(precision)
.replace(".", "")
.slice(0, precision);
return sprintf(
"%04d-%02d-%02dT%02d:%02d:%02d.%sZ",
year,
month,
day,
hour,
minute,
second,
millisecondStr
);
};
/**
* Duplicates a JulianDate instance.
*
* @param {JulianDate} julianDate The date to duplicate.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
*/
JulianDate.clone = function (julianDate, result) {
if (!defined(julianDate)) {
return undefined;
}
if (!defined(result)) {
return new JulianDate(
julianDate.dayNumber,
julianDate.secondsOfDay,
TimeStandard.TAI
);
}
result.dayNumber = julianDate.dayNumber;
result.secondsOfDay = julianDate.secondsOfDay;
return result;
};
/**
* Compares two instances.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Number} A negative value if left is less than right, a positive value if left is greater than right, or zero if left and right are equal.
*/
JulianDate.compare = function (left, right) {
//>>includeStart('debug', pragmas.debug);
if (!defined(left)) {
throw new DeveloperError("left is required.");
}
if (!defined(right)) {
throw new DeveloperError("right is required.");
}
//>>includeEnd('debug');
var julianDayNumberDifference = left.dayNumber - right.dayNumber;
if (julianDayNumberDifference !== 0) {
return julianDayNumberDifference;
}
return left.secondsOfDay - right.secondsOfDay;
};
/**
* Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {JulianDate} [left] The first instance.
* @param {JulianDate} [right] The second instance.
* @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
*/
JulianDate.equals = function (left, right) {
return (
left === right ||
(defined(left) &&
defined(right) &&
left.dayNumber === right.dayNumber &&
left.secondsOfDay === right.secondsOfDay)
);
};
/**
* Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
* each other. That is, in order for the dates to be considered equal (and for
* this function to return <code>true</code>), the absolute value of the difference between them, in
* seconds, must be less than <code>epsilon</code>.
*
* @param {JulianDate} [left] The first instance.
* @param {JulianDate} [right] The second instance.
* @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
* @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
*/
JulianDate.equalsEpsilon = function (left, right, epsilon) {
epsilon = defaultValue(epsilon, 0);
return (
left === right ||
(defined(left) &&
defined(right) &&
Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon)
);
};
/**
* Computes the total number of whole and fractional days represented by the provided instance.
*
* @param {JulianDate} julianDate The date.
* @returns {Number} The Julian date as single floating point number.
*/
JulianDate.totalDays = function (julianDate) {
//>>includeStart('debug', pragmas.debug);
if (!defined(julianDate)) {
throw new DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
return (
julianDate.dayNumber +
julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY
);
};
/**
* Computes the difference in seconds between the provided instance.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
*/
JulianDate.secondsDifference = function (left, right) {
//>>includeStart('debug', pragmas.debug);
if (!defined(left)) {
throw new DeveloperError("left is required.");
}
if (!defined(right)) {
throw new DeveloperError("right is required.");
}
//>>includeEnd('debug');
var dayDifference =
(left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
return dayDifference + (left.secondsOfDay - right.secondsOfDay);
};
/**
* Computes the difference in days between the provided instance.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
*/
JulianDate.daysDifference = function (left, right) {
//>>includeStart('debug', pragmas.debug);
if (!defined(left)) {
throw new DeveloperError("left is required.");
}
if (!defined(right)) {
throw new DeveloperError("right is required.");
}
//>>includeEnd('debug');
var dayDifference = left.dayNumber - right.dayNumber;
var secondDifference =
(left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
return dayDifference + secondDifference;
};
/**
* Computes the number of seconds the provided instance is ahead of UTC.
*
* @param {JulianDate} julianDate The date.
* @returns {Number} The number of seconds the provided instance is ahead of UTC
*/
JulianDate.computeTaiMinusUtc = function (julianDate) {
binarySearchScratchLeapSecond.julianDate = julianDate;
var leapSeconds = JulianDate.leapSeconds;
var index = binarySearch(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates
);
if (index < 0) {
index = ~index;
--index;
if (index < 0) {
index = 0;
}