forked from moment/moment-timezone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
moment-timezone.js
729 lines (606 loc) · 16.7 KB
/
moment-timezone.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
//! moment-timezone.js
//! version : 0.5.45
//! Copyright (c) JS Foundation and other contributors
//! license : MIT
//! github.com/moment/moment-timezone
(function (root, factory) {
"use strict";
/*global define*/
if (typeof module === 'object' && module.exports) {
module.exports = factory(require('moment')); // Node
} else if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else {
factory(root.moment); // Browser
}
}(this, function (moment) {
"use strict";
// Resolves es6 module loading issue
if (moment.version === undefined && moment.default) {
moment = moment.default;
}
// Do not load moment-timezone a second time.
// if (moment.tz !== undefined) {
// logError('Moment Timezone ' + moment.tz.version + ' was already loaded ' + (moment.tz.dataVersion ? 'with data from ' : 'without any data') + moment.tz.dataVersion);
// return moment;
// }
var VERSION = "0.5.45",
zones = {},
links = {},
countries = {},
names = {},
guesses = {},
cachedGuess;
if (!moment || typeof moment.version !== 'string') {
logError('Moment Timezone requires Moment.js. See https://momentjs.com/timezone/docs/#/use-it/browser/');
}
var momentVersion = moment.version.split('.'),
major = +momentVersion[0],
minor = +momentVersion[1];
// Moment.js version check
if (major < 2 || (major === 2 && minor < 6)) {
logError('Moment Timezone requires Moment.js >= 2.6.0. You are using Moment.js ' + moment.version + '. See momentjs.com');
}
/************************************
Unpacking
************************************/
function charCodeToInt(charCode) {
if (charCode > 96) {
return charCode - 87;
} else if (charCode > 64) {
return charCode - 29;
}
return charCode - 48;
}
function unpackBase60(string) {
var i = 0,
parts = string.split('.'),
whole = parts[0],
fractional = parts[1] || '',
multiplier = 1,
num,
out = 0,
sign = 1;
// handle negative numbers
if (string.charCodeAt(0) === 45) {
i = 1;
sign = -1;
}
// handle digits before the decimal
for (i; i < whole.length; i++) {
num = charCodeToInt(whole.charCodeAt(i));
out = 60 * out + num;
}
// handle digits after the decimal
for (i = 0; i < fractional.length; i++) {
multiplier = multiplier / 60;
num = charCodeToInt(fractional.charCodeAt(i));
out += num * multiplier;
}
return out * sign;
}
function arrayToInt (array) {
for (var i = 0; i < array.length; i++) {
array[i] = unpackBase60(array[i]);
}
}
function intToUntil (array, length) {
for (var i = 0; i < length; i++) {
array[i] = Math.round((array[i - 1] || 0) + (array[i] * 60000)); // minutes to milliseconds
}
array[length - 1] = Infinity;
}
function mapIndices (source, indices) {
var out = [], i;
for (i = 0; i < indices.length; i++) {
out[i] = source[indices[i]];
}
return out;
}
function unpack (string) {
var data = string.split('|'),
offsets = data[2].split(' '),
indices = data[3].split(''),
untils = data[4].split(' ');
arrayToInt(offsets);
arrayToInt(indices);
arrayToInt(untils);
intToUntil(untils, indices.length);
return {
name : data[0],
abbrs : mapIndices(data[1].split(' '), indices),
offsets : mapIndices(offsets, indices),
untils : untils,
population : data[5] | 0
};
}
/************************************
Zone object
************************************/
function Zone (packedString) {
if (packedString) {
this._set(unpack(packedString));
}
}
function closest (num, arr) {
var len = arr.length;
if (num < arr[0]) {
return 0;
} else if (len > 1 && arr[len - 1] === Infinity && num >= arr[len - 2]) {
return len - 1;
} else if (num >= arr[len - 1]) {
return -1;
}
var mid;
var lo = 0;
var hi = len - 1;
while (hi - lo > 1) {
mid = Math.floor((lo + hi) / 2);
if (arr[mid] <= num) {
lo = mid;
} else {
hi = mid;
}
}
return hi;
}
Zone.prototype = {
_set : function (unpacked) {
this.name = unpacked.name;
this.abbrs = unpacked.abbrs;
this.untils = unpacked.untils;
this.offsets = unpacked.offsets;
this.population = unpacked.population;
},
_index : function (timestamp) {
var target = +timestamp,
untils = this.untils,
i;
i = closest(target, untils);
if (i >= 0) {
return i;
}
},
countries : function () {
var zone_name = this.name;
return Object.keys(countries).filter(function (country_code) {
return countries[country_code].zones.indexOf(zone_name) !== -1;
});
},
parse : function (timestamp) {
var target = +timestamp,
offsets = this.offsets,
untils = this.untils,
max = untils.length - 1,
offset, offsetNext, offsetPrev, i;
for (i = 0; i < max; i++) {
offset = offsets[i];
offsetNext = offsets[i + 1];
offsetPrev = offsets[i ? i - 1 : i];
if (offset < offsetNext && tz.moveAmbiguousForward) {
offset = offsetNext;
} else if (offset > offsetPrev && tz.moveInvalidForward) {
offset = offsetPrev;
}
if (target < untils[i] - (offset * 60000)) {
return offsets[i];
}
}
return offsets[max];
},
abbr : function (mom) {
return this.abbrs[this._index(mom)];
},
offset : function (mom) {
logError("zone.offset has been deprecated in favor of zone.utcOffset");
return this.offsets[this._index(mom)];
},
utcOffset : function (mom) {
return this.offsets[this._index(mom)];
}
};
/************************************
Country object
************************************/
function Country (country_name, zone_names) {
this.name = country_name;
this.zones = zone_names;
}
/************************************
Current Timezone
************************************/
function OffsetAt(at) {
var timeString = at.toTimeString();
var abbr = timeString.match(/\([a-z ]+\)/i);
if (abbr && abbr[0]) {
// 17:56:31 GMT-0600 (CST)
// 17:56:31 GMT-0600 (Central Standard Time)
abbr = abbr[0].match(/[A-Z]/g);
abbr = abbr ? abbr.join('') : undefined;
} else {
// 17:56:31 CST
// 17:56:31 GMT+0800 (台北標準時間)
abbr = timeString.match(/[A-Z]{3,5}/g);
abbr = abbr ? abbr[0] : undefined;
}
if (abbr === 'GMT') {
abbr = undefined;
}
this.at = +at;
this.abbr = abbr;
this.offset = at.getTimezoneOffset();
}
function ZoneScore(zone) {
this.zone = zone;
this.offsetScore = 0;
this.abbrScore = 0;
}
ZoneScore.prototype.scoreOffsetAt = function (offsetAt) {
this.offsetScore += Math.abs(this.zone.utcOffset(offsetAt.at) - offsetAt.offset);
if (this.zone.abbr(offsetAt.at).replace(/[^A-Z]/g, '') !== offsetAt.abbr) {
this.abbrScore++;
}
};
function findChange(low, high) {
var mid, diff;
while ((diff = ((high.at - low.at) / 12e4 | 0) * 6e4)) {
mid = new OffsetAt(new Date(low.at + diff));
if (mid.offset === low.offset) {
low = mid;
} else {
high = mid;
}
}
return low;
}
function userOffsets() {
var startYear = new Date().getFullYear() - 2,
last = new OffsetAt(new Date(startYear, 0, 1)),
lastOffset = last.offset,
offsets = [last],
change, next, nextOffset, i;
for (i = 1; i < 48; i++) {
nextOffset = new Date(startYear, i, 1).getTimezoneOffset();
if (nextOffset !== lastOffset) {
// Create OffsetAt here to avoid unnecessary abbr parsing before checking offsets
next = new OffsetAt(new Date(startYear, i, 1));
change = findChange(last, next);
offsets.push(change);
offsets.push(new OffsetAt(new Date(change.at + 6e4)));
last = next;
lastOffset = nextOffset;
}
}
for (i = 0; i < 4; i++) {
offsets.push(new OffsetAt(new Date(startYear + i, 0, 1)));
offsets.push(new OffsetAt(new Date(startYear + i, 6, 1)));
}
return offsets;
}
function sortZoneScores (a, b) {
if (a.offsetScore !== b.offsetScore) {
return a.offsetScore - b.offsetScore;
}
if (a.abbrScore !== b.abbrScore) {
return a.abbrScore - b.abbrScore;
}
if (a.zone.population !== b.zone.population) {
return b.zone.population - a.zone.population;
}
return b.zone.name.localeCompare(a.zone.name);
}
function addToGuesses (name, offsets) {
var i, offset;
arrayToInt(offsets);
for (i = 0; i < offsets.length; i++) {
offset = offsets[i];
guesses[offset] = guesses[offset] || {};
guesses[offset][name] = true;
}
}
function guessesForUserOffsets (offsets) {
var offsetsLength = offsets.length,
filteredGuesses = {},
out = [],
checkedOffsets = {},
i, j, offset, guessesOffset;
for (i = 0; i < offsetsLength; i++) {
offset = offsets[i].offset;
if (checkedOffsets.hasOwnProperty(offset)) {
continue;
}
guessesOffset = guesses[offset] || {};
for (j in guessesOffset) {
if (guessesOffset.hasOwnProperty(j)) {
filteredGuesses[j] = true;
}
}
checkedOffsets[offset] = true;
}
for (i in filteredGuesses) {
if (filteredGuesses.hasOwnProperty(i)) {
out.push(names[i]);
}
}
return out;
}
function rebuildGuess () {
// use Intl API when available and returning valid time zone
try {
var intlName = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (intlName && intlName.length > 3) {
var name = names[normalizeName(intlName)];
if (name) {
return name;
}
logError("Moment Timezone found " + intlName + " from the Intl api, but did not have that data loaded.");
}
} catch (e) {
// Intl unavailable, fall back to manual guessing.
}
var offsets = userOffsets(),
offsetsLength = offsets.length,
guesses = guessesForUserOffsets(offsets),
zoneScores = [],
zoneScore, i, j;
for (i = 0; i < guesses.length; i++) {
zoneScore = new ZoneScore(getZone(guesses[i]), offsetsLength);
for (j = 0; j < offsetsLength; j++) {
zoneScore.scoreOffsetAt(offsets[j]);
}
zoneScores.push(zoneScore);
}
zoneScores.sort(sortZoneScores);
return zoneScores.length > 0 ? zoneScores[0].zone.name : undefined;
}
function guess (ignoreCache) {
if (!cachedGuess || ignoreCache) {
cachedGuess = rebuildGuess();
}
return cachedGuess;
}
/************************************
Global Methods
************************************/
function normalizeName (name) {
return (name || '').toLowerCase().replace(/\//g, '_');
}
function addZone (packed) {
var i, name, split, normalized;
if (typeof packed === "string") {
packed = [packed];
}
for (i = 0; i < packed.length; i++) {
split = packed[i].split('|');
name = split[0];
normalized = normalizeName(name);
zones[normalized] = packed[i];
names[normalized] = name;
addToGuesses(normalized, split[2].split(' '));
}
}
function getZone (name, caller) {
name = normalizeName(name);
var zone = zones[name];
var link;
if (zone instanceof Zone) {
return zone;
}
if (typeof zone === 'string') {
zone = new Zone(zone);
zones[name] = zone;
return zone;
}
// Pass getZone to prevent recursion more than 1 level deep
if (links[name] && caller !== getZone && (link = getZone(links[name], getZone))) {
zone = zones[name] = new Zone();
zone._set(link);
zone.name = names[name];
return zone;
}
return null;
}
function getNames () {
var i, out = [];
for (i in names) {
if (names.hasOwnProperty(i) && (zones[i] || zones[links[i]]) && names[i]) {
out.push(names[i]);
}
}
return out.sort();
}
function getCountryNames () {
return Object.keys(countries);
}
function addLink (aliases) {
var i, alias, normal0, normal1;
if (typeof aliases === "string") {
aliases = [aliases];
}
for (i = 0; i < aliases.length; i++) {
alias = aliases[i].split('|');
normal0 = normalizeName(alias[0]);
normal1 = normalizeName(alias[1]);
links[normal0] = normal1;
names[normal0] = alias[0];
links[normal1] = normal0;
names[normal1] = alias[1];
}
}
function addCountries (data) {
var i, country_code, country_zones, split;
if (!data || !data.length) return;
for (i = 0; i < data.length; i++) {
split = data[i].split('|');
country_code = split[0].toUpperCase();
country_zones = split[1].split(' ');
countries[country_code] = new Country(
country_code,
country_zones
);
}
}
function getCountry (name) {
name = name.toUpperCase();
return countries[name] || null;
}
function zonesForCountry(country, with_offset) {
country = getCountry(country);
if (!country) return null;
var zones = country.zones.sort();
if (with_offset) {
return zones.map(function (zone_name) {
var zone = getZone(zone_name);
return {
name: zone_name,
offset: zone.utcOffset(new Date())
};
});
}
return zones;
}
function loadData (data) {
addZone(data.zones);
addLink(data.links);
addCountries(data.countries);
tz.dataVersion = data.version;
}
function zoneExists (name) {
if (!zoneExists.didShowError) {
zoneExists.didShowError = true;
logError("moment.tz.zoneExists('" + name + "') has been deprecated in favor of !moment.tz.zone('" + name + "')");
}
return !!getZone(name);
}
function needsOffset (m) {
var isUnixTimestamp = (m._f === 'X' || m._f === 'x');
return !!(m._a && (m._tzm === undefined) && !isUnixTimestamp);
}
function logError (message) {
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
}
/************************************
moment.tz namespace
************************************/
function tz (input) {
var args = Array.prototype.slice.call(arguments, 0, -1),
name = arguments[arguments.length - 1],
out = moment.utc.apply(null, args),
zone;
if (!moment.isMoment(input) && needsOffset(out) && (zone = getZone(name))) {
out.add(zone.parse(out), 'minutes');
}
out.tz(name);
return out;
}
tz.version = VERSION;
tz.dataVersion = '';
tz._zones = zones;
tz._links = links;
tz._names = names;
tz._countries = countries;
tz.add = addZone;
tz.link = addLink;
tz.load = loadData;
tz.zone = getZone;
tz.zoneExists = zoneExists; // deprecated in 0.1.0
tz.guess = guess;
tz.names = getNames;
tz.Zone = Zone;
tz.unpack = unpack;
tz.unpackBase60 = unpackBase60;
tz.needsOffset = needsOffset;
tz.moveInvalidForward = true;
tz.moveAmbiguousForward = false;
tz.countries = getCountryNames;
tz.zonesForCountry = zonesForCountry;
/************************************
Interface with Moment.js
************************************/
var fn = moment.fn;
moment.tz = tz;
moment.defaultZone = null;
moment.updateOffset = function (mom, keepTime) {
var zone = moment.defaultZone,
offset;
if (mom._z === undefined) {
if (zone && needsOffset(mom) && !mom._isUTC && mom.isValid()) {
mom._d = moment.utc(mom._a)._d;
mom.utc().add(zone.parse(mom), 'minutes');
}
mom._z = zone;
}
if (mom._z) {
offset = mom._z.utcOffset(mom);
if (Math.abs(offset) < 16) {
offset = offset / 60;
}
if (mom.utcOffset !== undefined) {
var z = mom._z;
mom.utcOffset(-offset, keepTime);
mom._z = z;
} else {
mom.zone(offset, keepTime);
}
}
};
fn.tz = function (name, keepTime) {
if (name) {
if (typeof name !== 'string') {
throw new Error('Time zone name must be a string, got ' + name + ' [' + typeof name + ']');
}
this._z = getZone(name);
if (this._z) {
moment.updateOffset(this, keepTime);
} else {
logError("Moment Timezone has no data for " + name + ". See http://momentjs.com/timezone/docs/#/data-loading/.");
}
return this;
}
if (this._z) { return this._z.name; }
};
function abbrWrap (old) {
return function () {
if (this._z) { return this._z.abbr(this); }
return old.call(this);
};
}
function resetZoneWrap (old) {
return function () {
this._z = null;
return old.apply(this, arguments);
};
}
function resetZoneWrap2 (old) {
return function () {
if (arguments.length > 0) this._z = null;
return old.apply(this, arguments);
};
}
fn.zoneName = abbrWrap(fn.zoneName);
fn.zoneAbbr = abbrWrap(fn.zoneAbbr);
fn.utc = resetZoneWrap(fn.utc);
fn.local = resetZoneWrap(fn.local);
fn.utcOffset = resetZoneWrap2(fn.utcOffset);
moment.tz.setDefault = function(name) {
if (major < 2 || (major === 2 && minor < 9)) {
logError('Moment Timezone setDefault() requires Moment.js >= 2.9.0. You are using Moment.js ' + moment.version + '.');
}
moment.defaultZone = name ? getZone(name) : null;
return moment;
};
// Cloning a moment should include the _z property.
var momentProperties = moment.momentProperties;
if (Object.prototype.toString.call(momentProperties) === '[object Array]') {
// moment 2.8.1+
momentProperties.push('_z');
momentProperties.push('_a');
} else if (momentProperties) {
// moment 2.7.0
momentProperties._z = null;
}
// INJECT DATA
return moment;
}));