forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
date.js
4083 lines (3737 loc) · 112 KB
/
date.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
'use strict';
/***
* @module Date
* @description Date parsing and formatting, relative formats, number shortcuts,
* and locale support with default English locales.
*
***/
var DATE_OPTIONS = {
'newDateInternal': defaultNewDate
};
var LOCALE_ARRAY_FIELDS = [
'months', 'weekdays', 'units', 'numerals', 'placeholders',
'articles', 'tokens', 'timeMarkers', 'ampm', 'timeSuffixes',
'parse', 'timeParse', 'timeFrontParse', 'modifiers'
];
// Regex for stripping Timezone Abbreviations
var TIMEZONE_ABBREVIATION_REG = /\(([-+]\d{2,4}|\w{3,5})\)$/;
// Regex for years with 2 digits or less
var ABBREVIATED_YEAR_REG = /^'?(\d{1,2})$/;
// One minute in milliseconds
var MINUTES = 60 * 1000;
// Date unit indexes
var HOURS_INDEX = 3,
DAY_INDEX = 4,
WEEK_INDEX = 5,
MONTH_INDEX = 6,
YEAR_INDEX = 7;
// ISO Defaults
var ISO_FIRST_DAY_OF_WEEK = 1,
ISO_FIRST_DAY_OF_WEEK_YEAR = 4;
var CoreParsingTokens = {
'yyyy': {
param: 'year',
src: '[-−+]?\\d{4,6}'
},
'yy': {
param: 'year',
src: '\\d{2}'
},
'y': {
param: 'year',
src: '\\d'
},
'ayy': {
param: 'year',
src: '\'\\d{2}'
},
'MM': {
param: 'month',
src: '(?:1[012]|0?[1-9])'
},
'dd': {
param: 'date',
src: '(?:3[01]|[12][0-9]|0?[1-9])'
},
'hh': {
param: 'hour',
src: '(?:2[0-4]|[01]?[0-9])'
},
'mm': {
param: 'minute',
src: '[0-5]\\d'
},
'ss': {
param: 'second',
src: '[0-5]\\d(?:[,.]\\d+)?'
},
'tzHour': {
src: '[-−+](?:2[0-4]|[01]?[0-9])'
},
'tzMinute': {
src: '[0-5]\\d'
},
'iyyyy': {
param: 'year',
src: '(?:[-−+]?\\d{4}|[-−+]\\d{5,6})'
},
'ihh': {
param: 'hour',
src: '(?:2[0-4]|[01][0-9])(?:[,.]\\d+)?'
},
'imm': {
param: 'minute',
src: '[0-5]\\d(?:[,.]\\d+)?'
},
'GMT': {
param: 'utc',
src: 'GMT'
},
'Z': {
param: 'utc',
src: 'Z'
},
'timestamp': {
src: '\\d+'
}
};
var LocalizedParsingTokens = {
'year': {
base: 'yyyy|ayy',
requiresSuffix: true
},
'month': {
base: 'MM',
requiresSuffix: true
},
'date': {
base: 'dd',
requiresSuffix: true
},
'hour': {
base: 'hh',
requiresSuffixOr: ':'
},
'minute': {
base: 'mm'
},
'second': {
base: 'ss'
},
'num': {
src: '\\d+',
requiresNumerals: true
}
};
var CoreParsingFormats = [
{
// 12-1978
// 08-1978 (MDY)
src: '{MM}[-.\\/]{yyyy}'
},
{
// 12/08/1978
// 08/12/1978 (MDY)
time: true,
src: '{dd}[-\\/]{MM}(?:[-\\/]{yyyy|yy|y})?',
mdy: '{MM}[-\\/]{dd}(?:[-\\/]{yyyy|yy|y})?'
},
{
// 12.08.1978
// 08.12.1978 (MDY)
time: true,
src: '{dd}\\.{MM}(?:\\.{yyyy|yy|y})?',
mdy: '{MM}\\.{dd}(?:\\.{yyyy|yy|y})?',
localeCheck: function(loc) {
// Do not allow this format if the locale
// uses a period as a time separator.
return loc.timeSeparator !== '.';
}
},
{
// 1975-08-25
time: true,
src: '{yyyy}[-.\\/]{MM}(?:[-.\\/]{dd})?'
},
{
// .NET JSON
src: '\\\\/Date\\({timestamp}(?:[-+]\\d{4,4})?\\)\\\\/'
},
{
// ISO-8601
src: '{iyyyy}(?:-?{MM}(?:-?{dd}(?:T{ihh}(?::?{imm}(?::?{ss})?)?)?)?)?{tzOffset?}'
}
];
var CoreOutputFormats = {
'ISO8601': '{yyyy}-{MM}-{dd}T{HH}:{mm}:{ss}.{SSS}{Z}',
'RFC1123': '{Dow}, {dd} {Mon} {yyyy} {HH}:{mm}:{ss} {ZZ}',
'RFC1036': '{Weekday}, {dd}-{Mon}-{yy} {HH}:{mm}:{ss} {ZZ}'
};
var FormatTokensBase = [
{
ldml: 'Dow',
strf: 'a',
lowerToken: 'dow',
get: function(d, localeCode) {
return localeManager.get(localeCode).getWeekdayName(getWeekday(d), 2);
}
},
{
ldml: 'Weekday',
strf: 'A',
lowerToken: 'weekday',
allowAlternates: true,
get: function(d, localeCode, alternate) {
return localeManager.get(localeCode).getWeekdayName(getWeekday(d), alternate);
}
},
{
ldml: 'Mon',
strf: 'b h',
lowerToken: 'mon',
get: function(d, localeCode) {
return localeManager.get(localeCode).getMonthName(getMonth(d), 2);
}
},
{
ldml: 'Month',
strf: 'B',
lowerToken: 'month',
allowAlternates: true,
get: function(d, localeCode, alternate) {
return localeManager.get(localeCode).getMonthName(getMonth(d), alternate);
}
},
{
strf: 'C',
get: function(d) {
return getYear(d).toString().slice(0, 2);
}
},
{
ldml: 'd date day',
strf: 'd',
strfPadding: 2,
ldmlPaddedToken: 'dd',
ordinalToken: 'do',
get: function(d) {
return getDate(d);
}
},
{
strf: 'e',
get: function(d) {
return padNumber(getDate(d), 2, false, 10, ' ');
}
},
{
ldml: 'H 24hr',
strf: 'H',
strfPadding: 2,
ldmlPaddedToken: 'HH',
get: function(d) {
return getHours(d);
}
},
{
ldml: 'h hours 12hr',
strf: 'I',
strfPadding: 2,
ldmlPaddedToken: 'hh',
get: function(d) {
return getHours(d) % 12 || 12;
}
},
{
ldml: 'D',
strf: 'j',
strfPadding: 3,
ldmlPaddedToken: 'DDD',
get: function(d) {
var s = setUnitAndLowerToEdge(cloneDate(d), MONTH_INDEX);
return getDaysSince(d, s) + 1;
}
},
{
ldml: 'M',
strf: 'm',
strfPadding: 2,
ordinalToken: 'Mo',
ldmlPaddedToken: 'MM',
get: function(d) {
return getMonth(d) + 1;
}
},
{
ldml: 'm minutes',
strf: 'M',
strfPadding: 2,
ldmlPaddedToken: 'mm',
get: function(d) {
return callDateGet(d, 'Minutes');
}
},
{
ldml: 'Q',
get: function(d) {
return ceil((getMonth(d) + 1) / 3);
}
},
{
ldml: 'TT',
strf: 'p',
get: function(d, localeCode) {
return getMeridiemToken(d, localeCode);
}
},
{
ldml: 'tt',
strf: 'P',
get: function(d, localeCode) {
return getMeridiemToken(d, localeCode).toLowerCase();
}
},
{
ldml: 'T',
lowerToken: 't',
get: function(d, localeCode) {
return getMeridiemToken(d, localeCode).charAt(0);
}
},
{
ldml: 's seconds',
strf: 'S',
strfPadding: 2,
ldmlPaddedToken: 'ss',
get: function(d) {
return callDateGet(d, 'Seconds');
}
},
{
ldml: 'S ms',
strfPadding: 3,
ldmlPaddedToken: 'SSS',
get: function(d) {
return callDateGet(d, 'Milliseconds');
}
},
{
ldml: 'e',
strf: 'u',
ordinalToken: 'eo',
get: function(d) {
return getWeekday(d) || 7;
}
},
{
strf: 'U',
strfPadding: 2,
get: function(d) {
// Sunday first, 0-53
return getWeekNumber(d, false, 0);
}
},
{
ldml: 'W',
strf: 'V',
strfPadding: 2,
ordinalToken: 'Wo',
ldmlPaddedToken: 'WW',
get: function(d) {
// Monday first, 1-53 (ISO8601)
return getWeekNumber(d, true);
}
},
{
strf: 'w',
get: function(d) {
return getWeekday(d);
}
},
{
ldml: 'w',
ordinalToken: 'wo',
ldmlPaddedToken: 'ww',
get: function(d, localeCode) {
// Locale dependent, 1-53
var loc = localeManager.get(localeCode),
dow = loc.getFirstDayOfWeek(localeCode),
doy = loc.getFirstDayOfWeekYear(localeCode);
return getWeekNumber(d, true, dow, doy);
}
},
{
strf: 'W',
strfPadding: 2,
get: function(d) {
// Monday first, 0-53
return getWeekNumber(d, false);
}
},
{
ldmlPaddedToken: 'gggg',
ldmlTwoDigitToken: 'gg',
get: function(d, localeCode) {
return getWeekYear(d, localeCode);
}
},
{
strf: 'G',
strfPadding: 4,
strfTwoDigitToken: 'g',
ldmlPaddedToken: 'GGGG',
ldmlTwoDigitToken: 'GG',
get: function(d, localeCode) {
return getWeekYear(d, localeCode, true);
}
},
{
ldml: 'year',
ldmlPaddedToken: 'yyyy',
ldmlTwoDigitToken: 'yy',
strf: 'Y',
strfPadding: 4,
strfTwoDigitToken: 'y',
get: function(d) {
return getYear(d);
}
},
{
ldml: 'ZZ',
strf: 'z',
get: function(d) {
return getUTCOffset(d);
}
},
{
ldml: 'X',
get: function(d) {
return trunc(d.getTime() / 1000);
}
},
{
ldml: 'x',
get: function(d) {
return d.getTime();
}
},
{
ldml: 'Z',
get: function(d) {
return getUTCOffset(d, true);
}
},
{
ldml: 'z',
strf: 'Z',
get: function(d) {
// Note that this is not accurate in all browsing environments!
// https://github.com/moment/moment/issues/162
// It will continue to be supported for Node and usage with the
// understanding that it may be blank.
var match = d.toString().match(TIMEZONE_ABBREVIATION_REG);
// istanbul ignore next
return match ? match[1] : '';
}
},
{
strf: 'D',
alias: '%m/%d/%y'
},
{
strf: 'F',
alias: '%Y-%m-%d'
},
{
strf: 'r',
alias: '%I:%M:%S %p'
},
{
strf: 'R',
alias: '%H:%M'
},
{
strf: 'T',
alias: '%H:%M:%S'
},
{
strf: 'x',
alias: '{short}'
},
{
strf: 'X',
alias: '{time}'
},
{
strf: 'c',
alias: '{stamp}'
}
];
var DateUnits = [
{
name: 'millisecond',
method: 'Milliseconds',
multiplier: 1,
start: 0,
end: 999
},
{
name: 'second',
method: 'Seconds',
multiplier: 1000,
start: 0,
end: 59
},
{
name: 'minute',
method: 'Minutes',
multiplier: 60 * 1000,
start: 0,
end: 59
},
{
name: 'hour',
method: 'Hours',
multiplier: 60 * 60 * 1000,
start: 0,
end: 23
},
{
name: 'day',
alias: 'date',
method: 'Date',
ambiguous: true,
multiplier: 24 * 60 * 60 * 1000,
start: 1,
end: function(d) {
return getDaysInMonth(d);
}
},
{
name: 'week',
method: 'ISOWeek',
ambiguous: true,
multiplier: 7 * 24 * 60 * 60 * 1000
},
{
name: 'month',
method: 'Month',
ambiguous: true,
multiplier: 30.4375 * 24 * 60 * 60 * 1000,
start: 0,
end: 11
},
{
name: 'year',
method: 'FullYear',
ambiguous: true,
multiplier: 365.25 * 24 * 60 * 60 * 1000,
start: 0
}
];
/***
* @method getOption(name)
* @returns Mixed
* @accessor
* @short Gets an option used internally by Date.
* @example
*
* Sugar.Date.getOption('newDateInternal');
*
* @param {string} name
*
***
* @method setOption(name, value)
* @accessor
* @short Sets an option used internally by Date.
* @extra If `value` is `null`, the default value will be restored.
* @options
*
* newDateInternal Sugar's internal date constructor. Date methods often
* construct a `new Date()` internally as a reference point
* (`isToday`, relative formats like `tomorrow`, etc). This
* can be overridden if you need it to be something else.
* Most commonly, this allows you to return a shifted date
* to simulate a specific timezone, as dates in Javascript
* are always local.
*
* @example
*
* Sugar.Date.setOption('newDateInternal', function() {
* var d = new Date(), offset;
* offset = (d.getTimezoneOffset() - 600) * 60 * 1000; // Hawaii time!
* d.setTime(d.getTime() + offset);
* return d;
* });
*
* @signature setOption(options)
* @param {DateOptions} options
* @param {string} name
* @param {any} value
* @option {Function} newDateInternal
*
***/
var _dateOptions = defineOptionsAccessor(sugarDate, DATE_OPTIONS);
function setDateChainableConstructor() {
setChainableConstructor(sugarDate, createDate);
}
// General helpers
function getNewDate() {
return _dateOptions('newDateInternal')();
}
function defaultNewDate() {
return new Date;
}
function cloneDate(d) {
// Rhino environments have a bug where new Date(d) truncates
// milliseconds so need to call getTime() here.
var clone = new Date(d.getTime());
_utc(clone, !!_utc(d));
return clone;
}
function dateIsValid(d) {
return !isNaN(d.getTime());
}
function assertDateIsValid(d) {
if (!dateIsValid(d)) {
throw new TypeError('Date is not valid');
}
}
function getHours(d) {
return callDateGet(d, 'Hours');
}
function getWeekday(d) {
return callDateGet(d, 'Day');
}
function getDate(d) {
return callDateGet(d, 'Date');
}
function getMonth(d) {
return callDateGet(d, 'Month');
}
function getYear(d) {
return callDateGet(d, 'FullYear');
}
function setDate(d, val) {
callDateSet(d, 'Date', val);
}
function setMonth(d, val) {
callDateSet(d, 'Month', val);
}
function setYear(d, val) {
callDateSet(d, 'FullYear', val);
}
function getDaysInMonth(d) {
return 32 - callDateGet(new Date(getYear(d), getMonth(d), 32), 'Date');
}
function setWeekday(d, dow, dir) {
if (!isNumber(dow)) return;
var currentWeekday = getWeekday(d);
if (dir) {
// Allow a "direction" parameter to determine whether a weekday can
// be set beyond the current weekday in either direction.
var ndir = dir > 0 ? 1 : -1;
var offset = dow % 7 - currentWeekday;
if (offset && offset / abs(offset) !== ndir) {
dow += 7 * ndir;
}
}
setDate(d, getDate(d) + dow - currentWeekday);
return d.getTime();
}
// Normal callDateSet method with ability
// to handle ISOWeek setting as well.
function callDateSetWithWeek(d, method, value, safe) {
if (method === 'ISOWeek') {
setISOWeekNumber(d, value);
} else {
callDateSet(d, method, value, safe);
}
}
// UTC helpers
function isUTC(d) {
return !!_utc(d) || tzOffset(d) === 0;
}
function getUTCOffset(d, iso) {
var offset = _utc(d) ? 0 : tzOffset(d), hours, mins, colon;
colon = iso === true ? ':' : '';
if (!offset && iso) return 'Z';
hours = padNumber(trunc(-offset / 60), 2, true);
mins = padNumber(abs(offset % 60), 2);
return hours + colon + mins;
}
function tzOffset(d) {
return d.getTimezoneOffset();
}
// Argument helpers
function collectUpdateDateArguments(args, allowDuration) {
var arg1 = args[0], arg2 = args[1], params, reset;
if (allowDuration && isString(arg1)) {
params = getDateParamsFromString(arg1);
reset = arg2;
} else if (isNumber(arg1) && isNumber(arg2)) {
params = collectDateParamsFromArguments(args);
} else {
params = isObjectType(arg1) ? simpleClone(arg1) : arg1;
reset = arg2;
}
return [params, reset];
}
function collectDateParamsFromArguments(args) {
var params = {}, index = 0;
walkUnitDown(YEAR_INDEX, function(unit) {
var arg = args[index++];
if (isDefined(arg)) {
params[unit.name] = arg;
}
});
return params;
}
function getDateParamsFromString(str) {
var match, num, params = {};
match = str.match(/^(-?\d*[\d.]\d*)?\s?(\w+?)s?$/i);
if (match) {
if (isUndefined(num)) {
num = match[1] ? +match[1] : 1;
}
params[match[2].toLowerCase()] = num;
}
return params;
}
// Iteration helpers
// Years -> Milliseconds
function iterateOverDateUnits(fn, startIndex, endIndex) {
endIndex = endIndex || 0;
if (isUndefined(startIndex)) {
startIndex = YEAR_INDEX;
}
for (var index = startIndex; index >= endIndex; index--) {
if (fn(DateUnits[index], index) === false) {
break;
}
}
}
// Years -> Milliseconds using getLower/Higher methods
function walkUnitDown(unitIndex, fn) {
while (unitIndex >= 0) {
if (fn(DateUnits[unitIndex], unitIndex) === false) {
break;
}
unitIndex = getLowerUnitIndex(unitIndex);
}
}
// Moving lower from specific unit
function getLowerUnitIndex(index) {
if (index === MONTH_INDEX) {
return DAY_INDEX;
} else if (index === WEEK_INDEX) {
return HOURS_INDEX;
}
return index - 1;
}
// Moving higher from specific unit
function getHigherUnitIndex(index) {
return index === DAY_INDEX ? MONTH_INDEX : index + 1;
}
// Years -> Milliseconds checking all date params including "weekday"
function iterateOverDateParams(params, fn, startIndex, endIndex) {
function run(name, unit, i) {
var val = getDateParam(params, name);
if (isDefined(val)) {
fn(name, val, unit, i);
}
}
iterateOverDateUnits(function (unit, i) {
var result = run(unit.name, unit, i);
if (result !== false && i === DAY_INDEX) {
// Check for "weekday", which has a distinct meaning
// in the context of setting a date, but has the same
// meaning as "day" as a unit of time.
result = run('weekday', unit, i);
}
return result;
}, startIndex, endIndex);
}
// Years -> Days
function iterateOverHigherDateParams(params, fn) {
iterateOverDateParams(params, fn, YEAR_INDEX, DAY_INDEX);
}
// Advancing helpers
function advanceDate(d, unit, num, reset) {
var set = {};
set[unit] = num;
return updateDate(d, set, reset, 1);
}
function advanceDateWithArgs(d, args, dir) {
args = collectUpdateDateArguments(args, true);
return updateDate(d, args[0], args[1], dir);
}
// Edge helpers
function resetTime(d) {
return setUnitAndLowerToEdge(d, HOURS_INDEX);
}
function resetLowerUnits(d, unitIndex) {
return setUnitAndLowerToEdge(d, getLowerUnitIndex(unitIndex));
}
function moveToBeginningOfWeek(d, firstDayOfWeek) {
setWeekday(d, floor((getWeekday(d) - firstDayOfWeek) / 7) * 7 + firstDayOfWeek);
return d;
}
function moveToEndOfWeek(d, firstDayOfWeek) {
var target = firstDayOfWeek - 1;
setWeekday(d, ceil((getWeekday(d) - target) / 7) * 7 + target);
return d;
}
function moveToBeginningOfUnit(d, unitIndex, localeCode) {
if (unitIndex === WEEK_INDEX) {
moveToBeginningOfWeek(d, localeManager.get(localeCode).getFirstDayOfWeek());
}
return setUnitAndLowerToEdge(d, getLowerUnitIndex(unitIndex));
}
function moveToEndOfUnit(d, unitIndex, localeCode, stopIndex) {
if (unitIndex === WEEK_INDEX) {
moveToEndOfWeek(d, localeManager.get(localeCode).getFirstDayOfWeek());
}
return setUnitAndLowerToEdge(d, getLowerUnitIndex(unitIndex), stopIndex, true);
}
function setUnitAndLowerToEdge(d, startIndex, stopIndex, end) {
walkUnitDown(startIndex, function(unit, i) {
var val = end ? unit.end : unit.start;
if (isFunction(val)) {
val = val(d);
}
callDateSet(d, unit.method, val);
return !isDefined(stopIndex) || i > stopIndex;
});
return d;
}
// Param helpers
function getDateParamKey(params, key) {
return getOwnKey(params, key) ||
getOwnKey(params, key + 's') ||
(key === 'day' && getOwnKey(params, 'date'));
}
function getDateParam(params, key) {
return getOwn(params, getDateParamKey(params, key));
}
function deleteDateParam(params, key) {
delete params[getDateParamKey(params, key)];
}
function getUnitIndexForParamName(name) {
var params = {}, unitIndex;
params[name] = 1;
iterateOverDateParams(params, function(name, val, unit, i) {
unitIndex = i;
return false;
});
return unitIndex;
}
// Time distance helpers
function getDaysSince(d1, d2) {
return getTimeDistanceForUnit(d1, d2, DateUnits[DAY_INDEX]);
}
function getTimeDistanceForUnit(d1, d2, unit) {
var fwd = d2 > d1, num, tmp;
if (!fwd) {
tmp = d2;
d2 = d1;
d1 = tmp;
}
num = d2 - d1;
if (unit.multiplier > 1) {
num = trunc(num / unit.multiplier);
}
// For higher order with potential ambiguity, use the numeric calculation
// as a starting point, then iterate until we pass the target date. Decrement
// starting point by 1 to prevent overshooting the date due to inconsistencies
// in ambiguous units numerically. For example, calculating the number of days
// from the beginning of the year to August 5th at 11:59:59 by doing a simple
// d2 - d1 will produce different results depending on whether or not a
// timezone shift was encountered due to DST, however that should not have an
// effect on our calculation here, so subtract by 1 to ensure that the
// starting point has not already overshot our target date.
if (unit.ambiguous) {
d1 = cloneDate(d1);
if (num) {
num -= 1;
advanceDate(d1, unit.name, num);
}
while (d1 < d2) {
advanceDate(d1, unit.name, 1);
if (d1 > d2) {
break;
}
num += 1;
}
}
return fwd ? -num : num;
}
// Parsing helpers
function getYearFromAbbreviation(str, d, prefer) {
// Following IETF here, adding 1900 or 2000 depending on the last two digits.
// Note that this makes no accordance for what should happen after 2050, but
// intentionally ignoring this for now. https://www.ietf.org/rfc/rfc2822.txt
var val = +str, delta;
val += val < 50 ? 2000 : 1900;
if (prefer) {
delta = val - getYear(d);
if (delta / abs(delta) !== prefer) {
val += prefer * 100;
}
}
return val;
}
// Week number helpers
function setISOWeekNumber(d, num) {
if (isNumber(num)) {
// Intentionally avoiding updateDate here to prevent circular dependencies.
var isoWeek = cloneDate(d), dow = getWeekday(d);
moveToFirstDayOfWeekYear(isoWeek, ISO_FIRST_DAY_OF_WEEK, ISO_FIRST_DAY_OF_WEEK_YEAR);
setDate(isoWeek, getDate(isoWeek) + 7 * (num - 1));
setYear(d, getYear(isoWeek));
setMonth(d, getMonth(isoWeek));
setDate(d, getDate(isoWeek));
setWeekday(d, dow || 7);
}
return d.getTime();
}
function getWeekNumber(d, allowPrevious, firstDayOfWeek, firstDayOfWeekYear) {
var isoWeek, n = 0;
if (isUndefined(firstDayOfWeek)) {
firstDayOfWeek = ISO_FIRST_DAY_OF_WEEK;
}
if (isUndefined(firstDayOfWeekYear)) {
firstDayOfWeekYear = ISO_FIRST_DAY_OF_WEEK_YEAR;
}
// Moving to the end of the week allows for forward year traversal, ie
// Dec 29 2014 is actually week 01 of 2015.
isoWeek = moveToEndOfWeek(cloneDate(d), firstDayOfWeek);
moveToFirstDayOfWeekYear(isoWeek, firstDayOfWeek, firstDayOfWeekYear);
if (allowPrevious && d < isoWeek) {
// If the date is still before the start of the year, then it should be
// the last week of the previous year, ie Jan 1 2016 is actually week 53
// of 2015, so move to the beginning of the week to traverse the year.
isoWeek = moveToBeginningOfWeek(cloneDate(d), firstDayOfWeek);
moveToFirstDayOfWeekYear(isoWeek, firstDayOfWeek, firstDayOfWeekYear);
}
while (isoWeek <= d) {
// Doing a very simple walk to get the week number.
setDate(isoWeek, getDate(isoWeek) + 7);
n++;
}
return n;
}
// Week year helpers