Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

timezone-js

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

timezone-js - npm Package Compare versions

Comparing version 0.4.1 to 0.4.3

spec/tz.async.spec.js

6

package.json

@@ -13,3 +13,4 @@ {

"description": "JavaScript timezone library based on Olson timezone data",
"version": "0.4.1",
"version": "0.4.3",
"main": "src/date.js",
"homepage": "https://github.com/mde/timezone-js",

@@ -21,3 +22,3 @@ "repository": {

"scripts": {
"test": "jasmine-node spec"
"test": "jake test:init; jake test"
},

@@ -29,4 +30,5 @@ "engines": {

"devDependencies": {
"jake": "latest",
"jasmine-node": "latest"
}
}

@@ -30,3 +30,3 @@ # TimezoneJS.Date

If you use `timezoneJS.Date` with `Fleegix.js`, there's nothing else you need to do -- timezones for North America will be loaded and parsed on initial page load, and others will be downloaded and parsed on-the-fly, as needed. If you want to use this code with some other JavaScript toolkit, you'll need to define your own transport method in the `loadZoneFile` method.
If you use `timezoneJS.Date` with `Fleegix.js`, there's nothing else you need to do -- timezones for North America will be loaded and parsed on initial page load, and others will be downloaded and parsed on-the-fly, as needed. If you want to use this code with some other JavaScript toolkit, you'll need to overwrite your own transport method by setting `timezoneJS.timezone.transport = someFunction` method. Take a look at `test-utils.js` in `spec` for an example.

@@ -100,4 +100,7 @@ ## Usage

The src directory contains a command-line JavaScript script that can generate this kind of JSON data. **Note that this script requires the Rhino (Java) JavaScript engine to run, since the stock SpiderMonkey (C) engine doesn't come with file I/O capabilities.**
The src directory contains 2 command-line JavaScript scripts that can generate this kind of JSON data:
- `node-preparse.js`: Uses Node to preparse and populate data.
- `preparse.js`: This script requires the Rhino (Java) JavaScript engine to run, since the stock SpiderMonkey (C) engine doesn't come with file I/O capabilities.
Use the script like this:

@@ -107,2 +110,6 @@

Or:
node node-preparse.js zoneFileDirectory [exemplarCities] > outputfile.json
The first parameter is the directory where the script can find the Olson zoneinfo files. The second (optional) param should be a comma-delimited list of timzeone cities to create the JSON data for. If that parameter isn't passed, the script will generate the JSON data for all the files.

@@ -115,3 +122,10 @@

rhino preparse.js olson_files > all_cities.json
Or:
node node-preparse.js olson_files \
"Asia/Tokyo, America/New_York, Europe/London" \
> major_cities.json
node node-preparse.js olson_files > all_cities.json
Once you have your file of JSON data, set your loading scheme to `timezoneJS.timezone.loadingSchemes.MANUAL_LOAD`, and load the JSON data with `loadZoneJSONData`, like this:

@@ -123,3 +137,3 @@

Since the limited set of data will be much smaller than any of the zoneinfo files, and the JSON data is deserialized with `eval`, this method is significantly faster than the default setup. However, it only works if you know beforehand exactly what timezones you want to use.
Since the limited set of data will be much smaller than any of the zoneinfo files, and the JSON data is deserialized with `eval` or `JSON.parse`, this method is significantly faster than the default setup. However, it only works if you know beforehand exactly what timezones you want to use.

@@ -137,12 +151,8 @@ ## Compressing

## Development
This project use [Jake](https://github.com/mde/jake) to build. In order to see available tasks, do `jake -T`. The build sequence is:
- `jake test:init`: Download and extract tz files to `lib/tz`.
- `jake test`: Run `jasmine-node`.
Feel free to fork and modify at your own will.
The source code is annotated and doc can be generated with `docco`
### Testing
This library requires timezone info from [IANA database](http://www.iana.org/time-zones). Download the data and put timezone files into lib/tz
It also uses jasmine-node as the testing framework. In order to run the tests, do `npm test`
Feel free to add more tests.
The source code is annotated and doc can be generated with `jake doc`.

@@ -10,3 +10,3 @@ var TestUtils = require('./test-utils')

it('should format string correctly in toString', function () {
it('should format string correctly in toISOString', function () {
var date = new timezoneJS.Date();

@@ -17,4 +17,4 @@ expect(date.toISOString()).toMatch(/[\d]{4}(-[\d]{2}){2}T([\d]{2}:){2}[\d]{2}.[\d]{3}/);

it('should get date correctly from UTC (2011-10-28T12:44:22.172000000)', function () {
var date = new timezoneJS.Date(2011,9,28,12,44,22,172,true);
expect(date.getTime()).toEqual(1319805862000);
var date = new timezoneJS.Date(2011,9,28,12,44,22,172,'Etc/UTC');
expect(date.getTime()).toEqual(1319805862172);
expect(date.toString()).toEqual('2011-10-28 12:44:22');

@@ -25,3 +25,3 @@ expect(date.toString('yyyy-MM-dd')).toEqual('2011-10-28');

it('should format 2011-10-28T12:44:22.172 UTC to different formats correctly', function () {
var date = new timezoneJS.Date(2011,9,28,12,44,22,172,true);
var date = new timezoneJS.Date(2011,9,28,12,44,22,172,'Etc/UTC');
expect(date.toString('MMM dd yyyy')).toEqual('Oct 28 2011');

@@ -33,14 +33,178 @@ expect(date.toString('MMM dd yyyy HH:mm:ss k')).toEqual('Oct 28 2011 12:44:22 PM');

it('should format 2011-10-28T12:44:22.172 UTC to different formats and tz correctly', function () {
var date = new timezoneJS.Date(2011,9,28,12,44,22,172,true);
var date = new timezoneJS.Date(2011,9,28,12,44,22,172,'Etc/UTC');
expect(date.toString('MMM dd yyyy', 'America/New_York')).toEqual('Oct 28 2011');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z', 'America/New_York')).toEqual('Oct 28 2011 08:44:22 AM EDT');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z', 'Asia/Bangkok')).toEqual('Oct 28 2011 07:44:22 PM ICT');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z', 'Asia/Shanghai')).toEqual('Oct 28 2011 08:44:22 PM CST');
});
it('should format 2011-02-28T12:44:22.172 UTC (before daylight) to different formats and tz correctly', function () {
var date = new timezoneJS.Date(2011,1,28,12,44,22,172,true);
expect(date.toString('MMM dd yyyy', 'America/New_York')).toEqual('Feb 28 2011');
var date = new timezoneJS.Date(2011,1,28,12,44,22,172,'Etc/UTC');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z', 'America/New_York')).toEqual('Feb 28 2011 07:44:22 AM EST');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z', 'Asia/Bangkok')).toEqual('Feb 28 2011 07:44:22 PM ICT');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z', 'Indian/Cocos')).toEqual('Feb 28 2011 07:14:22 PM CCT');
});
it('should convert dates from UTC to a timezone correctly', function () {
var date = new timezoneJS.Date(2011,1,28,12,44,22,172,'Etc/UTC');
date.setTimezone('America/Los_Angeles');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z')).toEqual('Feb 28 2011 04:44:22 AM PST');
expect(date.getTime()).toEqual(1298897062172);
expect(date.getHours()).toEqual(4);
});
it('should convert dates from a timezone to UTC correctly', function () {
var date = new timezoneJS.Date(2007, 9, 31, 10, 30, 22, 'America/Los_Angeles');
date.setTimezone('Etc/GMT');
expect(date.getTime()).toEqual(1193851822000);
expect(date.toString('MMM dd yyyy HH:mm:ss k Z')).toEqual('Oct 31 2007 05:30:22 PM UTC');
expect(date.getHours()).toEqual(17);
});
it('should convert dates from one timezone to another correctly', function () {
var dtA = new timezoneJS.Date(2007, 9, 31, 10, 30, 'America/Los_Angeles');
dtA.setTimezone('America/Chicago');
expect(dtA.getTime()).toEqual(1193851800000);
expect(dtA.toString()).toEqual('2007-10-31 12:30:00');
});
it('should convert dates from unix time properly', function () {
var dtA = new timezoneJS.Date(1193851800000);
dtA.setTimezone('America/Chicago');
expect(dtA.getTime()).toEqual(1193851800000);
expect(dtA.toString()).toEqual('2007-10-31 12:30:00');
});
it('should output toISOString correctly', function () {
var dtA = new Date()
, dt = new timezoneJS.Date();
dtA.setTime(dtA.getTime());
expect(dt.getTime()).toEqual(dtA.getTime());
expect(dt.toISOString()).toEqual(dtA.toISOString());
});
it('should output toGMTString correctly', function () {
var dtA = new Date()
, dt = new timezoneJS.Date();
dtA.setTime(dtA.getTime());
expect(dt.getTime()).toEqual(dtA.getTime());
expect(dt.toGMTString()).toEqual(dtA.toGMTString());
});
it('should output toJSON correctly', function () {
var dtA = new Date()
, dt = new timezoneJS.Date();
dtA.setTime(dtA.getTime());
expect(dt.getTime()).toEqual(dtA.getTime());
expect(dt.toJSON()).toEqual(dtA.toJSON());
});
it('should take in millis as constructor', function () {
var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA.getTime());
expect(dt.getTime()).toEqual(dtA.getTime());
expect(dt.toJSON()).toEqual(dtA.toJSON());
});
it('should take in Date object as constructor', function () {
var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA);
expect(dt.getTime()).toEqual(dtA.getTime());
expect(dt.toJSON()).toEqual(dtA.toJSON());
});
it('should take in millis and tz as constructor', function () {
var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA.getTime(), 'Asia/Bangkok');
expect(dt.getTime()).toEqual(-7 * 3600 * 1000);
});
it('should take in Date object as constructor', function () {
var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA, 'Asia/Bangkok');
expect(dt.getTime()).toEqual(-7 * 3600 * 1000);
});
it('should take in String and Asia/Bangkok as constructor', function () {
var dt = new timezoneJS.Date('2012-01-01T15:00:00.000', 'Asia/Bangkok');
expect(dt.toString()).toEqual('2012-01-01 15:00:00');
expect(dt.toString('yyyy-MM-ddTHH:mm:ss.SSS', 'America/New_York')).toEqual('2012-01-01T03:00:00.000');
expect(dt.toString('yyyy-MM-ddTHH:mm:ss.SSS')).toEqual('2012-01-01T15:00:00.000');
});
it('should take in String and Etc/UTC as constructor', function () {
var dt = new timezoneJS.Date('2012-01-01T15:00:00.000', 'Etc/UTC');
expect(dt.toString('yyyy-MM-ddTHH:mm:ss.SSS', 'America/New_York')).toEqual('2012-01-01T10:00:00.000');
expect(dt.toString('yyyy-MM-ddTHH:mm:ss.SSS')).toEqual('2012-01-01T15:00:00.000');
});
it('should take in String as constructor', function () {
var dtA = new Date()
, dt = new timezoneJS.Date(dtA.toJSON());
expect(dt.toJSON()).toEqual(dtA.toJSON());
});
it('should be able to set hours', function () {
var dtA = new Date(0)
, dt = new timezoneJS.Date(0, 'Etc/UTC');
dt.setHours(6);
expect(dt.getHours()).toEqual(6);
});
it('should be able to set date without altering others', function () {
var dt = new timezoneJS.Date(2012, 2, 2, 5, 0, 0, 0, 'America/Los_Angeles')
, dt2 = new timezoneJS.Date(2011, 4, 15, 23, 0, 0, 0, 'Asia/Bangkok');
var hours = dt.getHours();
dt.setDate(1);
expect(dt.getHours()).toEqual(hours);
hours = dt2.getHours();
dt2.setDate(2);
expect(dt2.getHours()).toEqual(hours);
});
it('should be able to set UTC date without altering others', function () {
var dt = new timezoneJS.Date(2012, 2, 2, 5, 0, 0, 0, 'America/Los_Angeles');
var hours = dt.getUTCHours();
dt.setUTCDate(1);
expect(dt.getUTCHours()).toEqual(hours);
});
it('should adjust daylight saving correctly', function () {
var dt1 = new timezoneJS.Date('2012-03-11T03:00:00', 'America/Chicago');
expect(dt1.getTimezoneAbbreviation()).toEqual('CDT');
var dt2 = new timezoneJS.Date('2012-03-11T01:59:59', 'America/Chicago');
expect(dt2.getTimezoneAbbreviation()).toEqual('CST');
expect(dt2.getTimezoneOffset()).toEqual(360);
});
it('should be able to clone itself', function () {
var dt = new timezoneJS.Date(0, 'America/Chicago')
, dtA = dt.clone();
expect(dt.getTime()).toEqual(dtA.getTime());
expect(dt.toString()).toEqual(dtA.toString());
expect(dt.getTimezoneOffset()).toEqual(dtA.getTimezoneOffset());
expect(dt.getTimezoneAbbreviation()).toEqual(dtA.getTimezoneAbbreviation());
});
});

@@ -13,3 +13,16 @@ var fs = require('fs');

var timezoneJS = (function (timezoneJS) {
var init = function (timezoneJS, options) {
var opts = {
async: false,
loadingScheme: timezoneJS.timezone.loadingSchemes.LAZY_LOAD
};
for (var k in (options || {})) {
opts[k] = options[k];
}
//Reset everything
timezoneJS.timezone.zones = {};
timezoneJS.timezone.rules = {};
timezoneJS.timezone.loadedZones = {};
//Set up again
timezoneJS.timezone.zoneFileBasePath = 'lib/tz';

@@ -27,9 +40,9 @@ timezoneJS.timezone.transport = function (opts) {

};
timezoneJS.timezone.defaultZoneFile = ['asia', 'backward', 'northamerica', 'southamerica', 'europe'];
timezoneJS.timezone.init({async: false});
timezoneJS.timezone.loadingScheme = opts.loadingScheme;
timezoneJS.timezone.init(opts);
return timezoneJS;
})(require('../src/date'));
};
TestUtils.getTimezoneJS = function () {
return timezoneJS;
TestUtils.getTimezoneJS = function (options) {
return init(require('../src/date'), options);
}

@@ -36,0 +49,0 @@

@@ -1,2 +0,1 @@

// timezoneJS Library
// -----

@@ -78,3 +77,3 @@ // The `timezoneJS.Date` object gives you full-blown timezone support, independent from the timezone set on the end-user's machine running the browser. It uses the Olson zoneinfo files for its timezone data.

return s;
}
};

@@ -94,3 +93,3 @@ // Abstraction layer for different transport layers, including fleegix/jQuery/Zepto

var _transport = function (opts) {
if ((!fleegix || typeof fleegix.xhr === 'undefined') && typeof $.ajax === 'undefined') {
if ((!fleegix || typeof fleegix.xhr === 'undefined') && (!$ || typeof $.ajax === 'undefined')) {
throw new Error('Please use the Fleegix.js XHR module, jQuery ajax, Zepto ajax, or define your own transport mechanism for downloading zone files.');

@@ -124,53 +123,48 @@ }

var args = Array.prototype.slice.apply(arguments)
, t = null
, dt = null
, tz = null
, utc = false;
, arr = [];
// If 1st argument is an array, we can use it as a list of arguments itself
//We support several different constructors, including all the ones from `Date` object
// with a timezone string at the end.
//
//- `[tz]`: Returns object with time in `tz` specified.
//
// - `utcMillis`, `[tz]`: Return object with UTC time = `utcMillis`, in `tz`.
//
// - `Date`, `[tz]`: Returns object with UTC time = `Date.getTime()`, in `tz`.
//
// - `year, month, [date,] [hours,] [minutes,] [seconds,] [millis,] [tz]: Same as `Date` object
// with tz.
//
// - `Array`: Can be any combo of the above.
//
//If 1st argument is an array, we can use it as a list of arguments itself
if (Object.prototype.toString.call(args[0]) === '[object Array]') {
args = args[0];
}
// No args -- create a floating date based on the current local offset
if (!args.length) {
dt = new Date();
if (typeof args[args.length - 1] === 'string' && /^[a-zA-Z]+\//gi.test(args[args.length - 1])) {
tz = args.pop();
}
// Date string or timestamp -- assumes floating
else if (args.length === 1) {
dt = new Date(args[0]);
}
// year, month, [date,] [hours,] [minutes,] [seconds,] [milliseconds,] [tzId,] [utc]
else {
t = args[args.length - 1];
// Last arg is utc, then the next to last would be timezone
if (typeof t === 'boolean') {
utc = args.pop();
tz = args.pop();
}
// Last arg is tzId
else if (typeof t === 'string') {
tz = args.pop();
utc = (tz === 'Etc/UTC' || tz === 'Etc/GMT');
}
// Date string (e.g., '12/27/2006')
t = args[args.length - 1];
if (typeof t === 'string') {
switch (args.length) {
case 0:
dt = new Date();
break;
case 1:
dt = new Date(args[0]);
}
// Date part numbers
else {
var a = [];
for (var i = 0; i < 8; i++) {
a[i] = args[i] || 0;
break;
default:
for (var i = 0; i < 7; i++) {
arr[i] = args[i] || 0;
}
dt = new Date(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
}
dt = new Date(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6]);
break;
}
this._useCache = false;
this._tzInfo = {};
this._tzAbbr = '';
this._extractTimeArray = function () {
return [this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.milliseconds, this.timezone];
};
this._useCache = false;
this._tzInfo = {};
this._day = 0;

@@ -185,4 +179,8 @@ this.year = 0;

this.timezone = tz || null;
this.utc = utc || false;
this.setFromDateObjProxy(dt);
this.utc = tz === 'Etc/UTC' || tz === 'Etc/GMT';
//Tricky part:
// For the cases where there are 1/2 arguments: `timezoneJS.Date(millis, [tz])` and `timezoneJS.Date(Date, [tz])`. The
// Date `dt` created should be in UTC. Thus the way I detect such cases is to determine if `arr` is not populated & `tz`
// is specified. Because if `tz` is not specified, `dt` can be in local time.
this.setFromDateObjProxy(dt, !arr.length && tz);
};

@@ -257,3 +255,3 @@

setUTCSeconds: function (n) { this.setUTCAttribute('seconds', n); },
toGMTString: function () { return this.toString('EEE, dd MMM yyyy HH:mm:ss Z', 'GMT'); },
toGMTString: function () { return this.toString('EEE, dd MMM yyyy HH:mm:ss Z', 'Etc/GMT'); },
toLocaleString: function () {},

@@ -263,3 +261,4 @@ toLocaleDateString: function () {},

toSource: function () {},
toISOString: function () { return this.toString('yyyy-MM-ddTHH:mm:ss.SSS'); },
toISOString: function () { return this.toString('yyyy-MM-ddTHH:mm:ss.SSS', 'Etc/UTC') + 'Z'; },
toJSON: function () { return this.toISOString(); },
// Allows different format following ISO8601 format:

@@ -275,3 +274,3 @@ toString: function (format, tz) {

_this = this.clone();
_this.setUTCMinutes(_this.getUTCMinutes() - tzInfo.tzOffset);
_this.setTimezone(tz);
}

@@ -334,2 +333,3 @@ var hours = _this.getHours();

this._day = fromUTC ? dt.getUTCDay() : dt.getDay();
this._dateProxy = dt;
this._useCache = false;

@@ -344,3 +344,3 @@ },

if (isNaN(n)) { throw new Error('Units must be a number.'); }
var dt = new Date(this._extractTimeArray());
var dt = this._dateProxy;
var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);

@@ -359,7 +359,12 @@ dt['set' + meth](n);

setTimezone: function (tz) {
if (tz === 'Etc/UTC' || tz === 'Etc/GMT') {
this.utc = true;
}
var previousOffset = this.getTimezoneInfo().tzOffset;
this.utc = tz === 'Etc/UTC' || tz === 'Etc/GMT';
this.timezone = tz;
this._useCache = false;
// Create a new time that offsets by the delta of the two timezones
var _this = this.clone();
_this.setUTCMinutes(_this.getUTCMinutes() - this.getTimezoneInfo().tzOffset + previousOffset);
this.setFromDateObjProxy(_this, this.utc);
},

@@ -385,10 +390,8 @@ removeTimezone: function () {

a = Math.floor(y / 100);
var b = 2 - a + Math.floor(a / 4);
jDt = Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d + b - 1524;
var b = 2 - a + Math.floor(a / 4)
, jDt = Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d + b - 1524;
return jDt;
},
getLocalOffset: function () {
var dt = this;
var d = new Date(dt.getYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds());
return d.getTimezoneOffset();
return this._dateProxy.getTimezoneOffset();
}

@@ -399,11 +402,9 @@ };

timezoneJS.timezone = new function () {
var _this = this;
var monthMap = {};
var dayMap = {};
var regionMap = {'EST':'northamerica','MST':'northamerica','HST':'northamerica','EST5EDT':'northamerica','CST6CDT':'northamerica','MST7MDT':'northamerica','PST8PDT':'northamerica','America':'northamerica','Pacific':'australasia','Atlantic':'europe','Africa':'africa','Indian':'africa','Antarctica':'antarctica','Asia':'asia','Australia':'australasia','Europe':'europe','WET':'europe','CET':'europe','MET':'europe','EET':'europe'};
var regionExceptions = {'Pacific/Honolulu':'northamerica','Atlantic/Bermuda':'northamerica','Atlantic/Cape_Verde':'africa','Atlantic/St_Helena':'africa','Indian/Kerguelen':'antarctica','Indian/Chagos':'asia','Indian/Maldives':'asia','Indian/Christmas':'australasia','Indian/Cocos':'australasia','America/Danmarkshavn':'europe','America/Scoresbysund':'europe','America/Godthab':'europe','America/Thule':'europe','Asia/Yekaterinburg':'europe','Asia/Omsk':'europe','Asia/Novosibirsk':'europe','Asia/Krasnoyarsk':'europe','Asia/Irkutsk':'europe','Asia/Yakutsk':'europe','Asia/Vladivostok':'europe','Asia/Sakhalin':'europe','Asia/Magadan':'europe','Asia/Kamchatka':'europe','Asia/Anadyr':'europe','Africa/Ceuta':'europe','America/Argentina/Buenos_Aires':'southamerica','America/Argentina/Cordoba':'southamerica','America/Argentina/Tucuman':'southamerica','America/Argentina/La_Rioja':'southamerica','America/Argentina/San_Juan':'southamerica','America/Argentina/Jujuy':'southamerica','America/Argentina/Catamarca':'southamerica','America/Argentina/Mendoza':'southamerica','America/Argentina/Rio_Gallegos':'southamerica','America/Argentina/Ushuaia':'southamerica','America/Aruba':'southamerica','America/La_Paz':'southamerica','America/Noronha':'southamerica','America/Belem':'southamerica','America/Fortaleza':'southamerica','America/Recife':'southamerica','America/Araguaina':'southamerica','America/Maceio':'southamerica','America/Bahia':'southamerica','America/Sao_Paulo':'southamerica','America/Campo_Grande':'southamerica','America/Cuiaba':'southamerica','America/Porto_Velho':'southamerica','America/Boa_Vista':'southamerica','America/Manaus':'southamerica','America/Eirunepe':'southamerica','America/Rio_Branco':'southamerica','America/Santiago':'southamerica','Pacific/Easter':'southamerica','America/Bogota':'southamerica','America/Curacao':'southamerica','America/Guayaquil':'southamerica','Pacific/Galapagos':'southamerica','Atlantic/Stanley':'southamerica','America/Cayenne':'southamerica','America/Guyana':'southamerica','America/Asuncion':'southamerica','America/Lima':'southamerica','Atlantic/South_Georgia':'southamerica','America/Paramaribo':'southamerica','America/Port_of_Spain':'southamerica','America/Montevideo':'southamerica','America/Caracas':'southamerica'};
var _this = this
, monthMap = {}
, dayMap = {}
, regionMap = {'EST':'northamerica','MST':'northamerica','HST':'northamerica','EST5EDT':'northamerica','CST6CDT':'northamerica','MST7MDT':'northamerica','PST8PDT':'northamerica','America':'northamerica','Pacific':'australasia','Atlantic':'europe','Africa':'africa','Indian':'africa','Antarctica':'antarctica','Asia':'asia','Australia':'australasia','Europe':'europe','WET':'europe','CET':'europe','MET':'europe','EET':'europe'}
, regionExceptions = {'Etc/GMT':'etcetera','Etc/UTC':'etcetera','Pacific/Honolulu':'northamerica','Atlantic/Bermuda':'northamerica','Atlantic/Cape_Verde':'africa','Atlantic/St_Helena':'africa','Indian/Kerguelen':'antarctica','Indian/Chagos':'asia','Indian/Maldives':'asia','Indian/Christmas':'australasia','Indian/Cocos':'australasia','America/Danmarkshavn':'europe','America/Scoresbysund':'europe','America/Godthab':'europe','America/Thule':'europe','Asia/Yekaterinburg':'europe','Asia/Omsk':'europe','Asia/Novosibirsk':'europe','Asia/Krasnoyarsk':'europe','Asia/Irkutsk':'europe','Asia/Yakutsk':'europe','Asia/Vladivostok':'europe','Asia/Sakhalin':'europe','Asia/Magadan':'europe','Asia/Kamchatka':'europe','Asia/Anadyr':'europe','Africa/Ceuta':'europe','America/Argentina/Buenos_Aires':'southamerica','America/Argentina/Cordoba':'southamerica','America/Argentina/Tucuman':'southamerica','America/Argentina/La_Rioja':'southamerica','America/Argentina/San_Juan':'southamerica','America/Argentina/Jujuy':'southamerica','America/Argentina/Catamarca':'southamerica','America/Argentina/Mendoza':'southamerica','America/Argentina/Rio_Gallegos':'southamerica','America/Argentina/Ushuaia':'southamerica','America/Aruba':'southamerica','America/La_Paz':'southamerica','America/Noronha':'southamerica','America/Belem':'southamerica','America/Fortaleza':'southamerica','America/Recife':'southamerica','America/Araguaina':'southamerica','America/Maceio':'southamerica','America/Bahia':'southamerica','America/Sao_Paulo':'southamerica','America/Campo_Grande':'southamerica','America/Cuiaba':'southamerica','America/Porto_Velho':'southamerica','America/Boa_Vista':'southamerica','America/Manaus':'southamerica','America/Eirunepe':'southamerica','America/Rio_Branco':'southamerica','America/Santiago':'southamerica','Pacific/Easter':'southamerica','America/Bogota':'southamerica','America/Curacao':'southamerica','America/Guayaquil':'southamerica','Pacific/Galapagos':'southamerica','Atlantic/Stanley':'southamerica','America/Cayenne':'southamerica','America/Guyana':'southamerica','America/Asuncion':'southamerica','America/Lima':'southamerica','Atlantic/South_Georgia':'southamerica','America/Paramaribo':'southamerica','America/Port_of_Spain':'southamerica','America/Montevideo':'southamerica','America/Caracas':'southamerica'};
/**
* { 'jan': 0, 'feb': 1, 'mar': 2, 'apr': 3,'may': 4, 'jun': 5, 'jul': 6, 'aug': 7, 'sep': 8, 'oct': 9, 'nov': 10, 'dec': 11 }
*/
//`{ 'jan': 0, 'feb': 1, 'mar': 2, 'apr': 3,'may': 4, 'jun': 5, 'jul': 6, 'aug': 7, 'sep': 8, 'oct': 9, 'nov': 10, 'dec': 11 }`
for (var i = 0; i < Months.length; i++) {

@@ -413,6 +414,4 @@ monthMap[Months[i].substr(0,3).toLowerCase()] = i;

/**
* {'sun': 0,'mon' :1, 'tue': 2, 'wed': 3, 'thu': 4, 'fri': 5, 'sat': 6 }
*/
for (var i = 0; i < Days.length; i++) {
//`{'sun': 0,'mon' :1, 'tue': 2, 'wed': 3, 'thu': 4, 'fri': 5, 'sat': 6 }`
for (i = 0; i < Days.length; i++) {
dayMap[Days[i].substr(0,3).toLowerCase()] = i;

@@ -424,5 +423,6 @@ }

var url = _this.zoneFileBasePath + '/' + fileName;
return !opts.async
return !opts || !opts.async
? _this.parseZones(_this.transport({ url : url, async : false }))
: _this.transport({
async: true,
url : url,

@@ -441,4 +441,5 @@ success : function (str) {

function getRegionForTimezone(tz) {
var exc = regionExceptions[tz];
var ret;
var exc = regionExceptions[tz]
, reg
, ret;
if (exc) return exc;

@@ -456,3 +457,3 @@ reg = tz.split('/')[0];

// This is for obvious legacy zones (e.g., Iceland) that don't even have a prefix like "America/" that look like normal zones
_this.loadZoneFile('backward', true);
_this.loadZoneFile('backward');
return getRegionForTimezone(tz);

@@ -481,9 +482,7 @@ }

if (!_this.loadedZones.backward) {
/**
* This is for backward entries like "America/Fort_Wayne" that
* getRegionForTimezone *thinks* it has a region file and zone
* for (e.g., America => 'northamerica'), but in reality it's a
* legacy zone we need the backward file for
*/
_this.loadZoneFile('backward', true);
//This is for backward entries like "America/Fort_Wayne" that
// getRegionForTimezone *thinks* it has a region file and zone
// for (e.g., America => 'northamerica'), but in reality it's a
// legacy zone we need the backward file for.
_this.loadZoneFile('backward');
return getZone(dt, tz);

@@ -503,8 +502,7 @@ }

}
var t = z[6] ? z[6] : '23:59:59';
t = parseTimeString(t);
t = parseTimeString(z[6] ? z[6] : '23:59:59');
var d = Date.UTC(yea, mon, dat, t[1], t[2], t[3]);
if (dt.getTime() < d) { break; }
}
if (i === zoneList.length) { throw new Error('No Zone found for "' + timezone + '" on ' + dt); }
if (i === zoneList.length) { throw new Error('No Zone found for "' + tz + '" on ' + dt); }
return zoneList[i];

@@ -514,4 +512,4 @@

function getBasicOffset(z) {
var off = parseTimeString(z[0]);
var adj = z[0].indexOf('-') === 0 ? -1 : 1
var off = parseTimeString(z[0])
, adj = z[0].indexOf('-') === 0 ? -1 : 1;
off = adj * (((off[1] * 60 + off[2]) * 60 + off[3]) * 1000);

@@ -521,6 +519,4 @@ return -off/60/1000;

/**
* if isUTC is true, date is given in UTC, otherwise it's given
* in local time (ie. date.getUTC*() returns local time components)
*/
//if isUTC is true, date is given in UTC, otherwise it's given
// in local time (ie. date.getUTC*() returns local time components)
function getRule(date, zone, isUTC) {

@@ -530,11 +526,12 @@ var ruleset = zone[1];

/**
* Convert a date to UTC. Depending on the 'type' parameter, the date
* parameter may be:
* 'u', 'g', 'z': already UTC (no adjustment)
* 's': standard time (adjust for time zone offset but not for DST)
* 'w': wall clock time (adjust for both time zone and DST offset)
*
* DST adjustment is done using the rule given as third argument
*/
//Convert a date to UTC. Depending on the 'type' parameter, the date
// parameter may be:
//
// - `u`, `g`, `z`: already UTC (no adjustment).
//
// - `s`: standard time (adjust for time zone offset but not for DST)
//
// - `w`: wall clock time (adjust for both time zone and DST offset).
//
// DST adjustment is done using the rule given as third argument.
var convertDateToUTC = function (date, type, rule) {

@@ -555,23 +552,25 @@ var offset = 0;

return new Date(date.getTime() + offset);
}
};
// Step 1: Find applicable rules for this year.
// Step 2: Sort the rules by effective date.
// Step 3: Check requested date to see if a rule has yet taken effect this year. If not,
// Step 4: Get the rules for the previous year. If there isn't an applicable rule for last year, then
// there probably is no current time offset since they seem to explicitly turn off the offset
// when someone stops observing DST.
// FIXME if this is not the case and we'll walk all the way back (ugh).
// Step 5: Sort the rules by effective date.
// Step 6: Apply the most recent rule before the current time.
//Step 1: Find applicable rules for this year.
//
//Step 2: Sort the rules by effective date.
//
//Step 3: Check requested date to see if a rule has yet taken effect this year. If not,
//
//Step 4: Get the rules for the previous year. If there isn't an applicable rule for last year, then
// there probably is no current time offset since they seem to explicitly turn off the offset
// when someone stops observing DST.
//
// FIXME if this is not the case and we'll walk all the way back (ugh).
//
//Step 5: Sort the rules by effective date.
//Step 6: Apply the most recent rule before the current time.
var convertRuleToExactDateAndTime = function (yearAndRule, prevRule) {
var year = yearAndRule[0]
, rule = yearAndRule[1]
, months = {} // Assume that the rule applies to the year of the given date.
, days = {};
, rule = yearAndRule[1]
, months = {} // Assume that the rule applies to the year of the given date.
, days = {};
/**
* { "Jan": 0, "Feb": 1, "Mar": 2, "Apr": 3, "May": 4, "Jun": 5, "Jul": 6, "Aug": 7, "Sep": 8, "Oct": 9, "Nov": 10, "Dec": 11 }
*/
//{ "Jan": 0, "Feb": 1, "Mar": 2, "Apr": 3, "May": 4, "Jun": 5, "Jul": 6, "Aug": 7, "Sep": 8, "Oct": 9, "Nov": 10, "Dec": 11 }
for (var i = 0; i < Months.length; i++) {

@@ -581,6 +580,4 @@ months[Months[i].substr(0, 3)] = i;

/**
* { "sun": 0, "mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5, "sat": 6 }
*/
for (var i = 0; i < Days.length; i++) {
//{ "sun": 0, "mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5, "sat": 6 }
for (i = 0; i < Days.length; i++) {
days[Days[i].substr(0, 3).toLowerCase()] = i;

@@ -592,10 +589,12 @@ }

if (!isNaN(rule[4])) { // If we have a specific date, use that!
//If we have a specific date, use that!
if (!isNaN(rule[4])) {
effectiveDate = new Date(Date.UTC(year, months[rule[3]], rule[4], hms[1], hms[2], hms[3], 0));
}
else { // Let's hunt for the date.
//Let's hunt for the date.
else {
var targetDay
, operator;
if (rule[4].substr(0, 4) === "last") { // Example: lastThu
, operator;
//Example: `lastThu`
if (rule[4].substr(0, 4) === "last") {
// Start at the last day of the month and work backward.

@@ -606,4 +605,5 @@ effectiveDate = new Date(Date.UTC(year, months[rule[3]] + 1, 1, hms[1] - 24, hms[2], hms[3], 0));

}
else { // Example: Sun>=15
// Start at the specified date.
//Example: `Sun>=15`
else {
//Start at the specified date.
effectiveDate = new Date(Date.UTC(year, months[rule[3]], rule[4].substr(5), hms[1], hms[2], hms[3], 0));

@@ -614,6 +614,8 @@ targetDay = days[rule[4].substr(0, 3).toLowerCase()];

var ourDay = effectiveDate.getUTCDay();
if (operator === ">=") { // Go forwards.
//Go forwards.
if (operator === ">=") {
effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay + ((targetDay < ourDay) ? 7 : 0)));
}
else { // Go backwards. Looking for the last of a certain day, or operator is "<=" (less likely).
//Go backwards. Looking for the last of a certain day, or operator is "<=" (less likely).
else {
effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay - ((targetDay > ourDay) ? 7 : 0)));

@@ -623,4 +625,4 @@ }

// if previous rule is given, correct for the fact that the starting time of the current
// rule may be specified in local time
//If previous rule is given, correct for the fact that the starting time of the current
// rule may be specified in local time.
if (prevRule) {

@@ -630,3 +632,3 @@ effectiveDate = convertDateToUTC(effectiveDate, hms[4], prevRule);

return effectiveDate;
}
};

@@ -636,14 +638,16 @@ var findApplicableRules = function (year, ruleset) {

for (var i = 0; ruleset && i < ruleset.length; i++) {
if (Number(ruleset[i][0]) <= year && // Exclude future rules.
//Exclude future rules.
if (Number(ruleset[i][0]) <= year &&
(
Number(ruleset[i][1]) >= year || // Date is in a set range.
(Number(ruleset[i][0]) === year && ruleset[i][1] === "only") || // Date is in an "only" year.
ruleset[i][1] === "max" // We're in a range from the start year to infinity.
// Date is in a set range.
Number(ruleset[i][1]) >= year ||
// Date is in an "only" year.
(Number(ruleset[i][0]) === year && ruleset[i][1] === "only") ||
//We're in a range from the start year to infinity.
ruleset[i][1] === "max"
)
) {
/**
* It's completely okay to have any number of matches here.
* Normally we should only see two, but that doesn't preclude other numbers of matches.
* These matches are applicable to this year.
*/
//It's completely okay to have any number of matches here.
// Normally we should only see two, but that doesn't preclude other numbers of matches.
// These matches are applicable to this year.
applicableRules.push([year, ruleset[i]]);

@@ -653,3 +657,3 @@ }

return applicableRules;
}
};

@@ -670,3 +674,3 @@ var compareDates = function (a, b, prev) {

return a - b;
}
};

@@ -678,3 +682,3 @@ var year = date.getUTCFullYear();

applicableRules.push(date);
// While sorting, the time zone in which the rule starting time is specified
//While sorting, the time zone in which the rule starting time is specified
// is ignored. This is ok as long as the timespan between two DST changes is

@@ -686,3 +690,4 @@ // larger than the DST offset, which is probably always true.

if (applicableRules.indexOf(date) < 2) { // If there are not enough past DST rules...
//If there are not enough past DST rules...
if (applicableRules.indexOf(date) < 2) {
applicableRules = applicableRules.concat(findApplicableRules(year-1, _this.rules[ruleset]));

@@ -694,9 +699,9 @@ applicableRules.sort(compareDates);

if (pinpoint > 1 && compareDates(date, applicableRules[pinpoint-1], applicableRules[pinpoint-2][1]) < 0) {
// the previous rule does not really apply, take the one before that
//The previous rule does not really apply, take the one before that.
return applicableRules[pinpoint - 2][1];
} else if (pinpoint > 0 && pinpoint < applicableRules.length - 1 && compareDates(date, applicableRules[pinpoint+1], applicableRules[pinpoint-1][1]) > 0) {
// the next rule does already apply, take that one
//The next rule does already apply, take that one.
return applicableRules[pinpoint + 1][1];
} else if (pinpoint === 0) {
// no applicable rule found in this and in previous year
//No applicable rule found in this and in previous year.
return null;

@@ -712,3 +717,3 @@ }

ret = ret/60/1000;
ret -= off
ret -= off;
ret = -Math.ceil(ret);

@@ -723,5 +728,5 @@ return ret;

if (rule) {
repl = rule[7]=='-'?'':rule[7];
repl = rule[7] === '-' ? '' : rule[7];
}
// FIXME: Right now just falling back to Standard --
//FIXME: Right now just falling back to Standard --
// apparently ought to use the last valid rule,

@@ -735,6 +740,6 @@ // although in practice that always ought to be Standard

else if (base.indexOf('/') > -1) {
// chose one of two alternative strings
//Chose one of two alternative strings.
var t = parseTimeString(rule[6]);
var isDst = (t[1])||(t[2])||(t[3]);
res = base.split("/",2)[isDst?1:0];
var isDst = t[1] || t[2] || t[3];
res = base.split("/", 2)[isDst ? 1 : 0];
} else {

@@ -754,5 +759,2 @@ res = base;

this.loadingScheme = this.loadingSchemes.LAZY_LOAD;
this.defaultZoneFile = this.loadingScheme === this.loadingSchemes.PRELOAD_ALL
? this.zoneFiles
: 'northamerica';
this.loadedZones = {};

@@ -763,5 +765,9 @@ this.zones = {};

this.init = function (o) {
var opts = { async: true };
var def = this.defaultZoneFile;
// Override default with any passed-in opts
var opts = { async: true }
, def = this.defaultZoneFile = this.loadingScheme === this.loadingSchemes.PRELOAD_ALL
? this.zoneFiles
: 'northamerica'
, done = 0
, callbackFn;
//Override default with any passed-in opts
for (var p in o) {

@@ -773,5 +779,9 @@ opts[p] = o[p];

}
if (opts.callback) {
throw new Error('Async load with callback is not supported for multiple default zonefiles.');
}
//Wraps callback function in another one that makes
// sure all files have been loaded.
callbackFn = opts.callback;
opts.callback = function () {
done++;
(done === def.length) && typeof callbackFn === 'function' && callbackFn();
};
for (var i = 0; i < def.length; i++) {

@@ -782,7 +792,5 @@ this.loadZoneFile(def[i], opts);

/**
* Get the zone files via XHR -- if the sync flag
* is set to true, it's being called by the lazy-loading
* mechanism, so the result needs to be returned inline
*/
//Get the zone files via XHR -- if the sync flag
// is set to true, it's being called by the lazy-loading
// mechanism, so the result needs to be returned inline.
this.loadZoneFile = function (fileName, opts) {

@@ -792,2 +800,6 @@ if (typeof this.zoneFileBasePath === 'undefined') {

}
//Ignore already loaded zones.
if (this.loadedZones[fileName]) {
return;
}
this.loadedZones[fileName] = true;

@@ -805,3 +817,3 @@ return builtInLoadZoneFile(fileName, opts);

}
}
};
return sync

@@ -822,13 +834,12 @@ ? processData(_this.transport({ url : url, async : false }))

var arr = [];
for (z in this.zones) { arr.push(z); }
for (var z in this.zones) { arr.push(z); }
return arr.sort();
};
this.parseZones = function (str) {
var s = ''
, lines = str.split('\n')
, arr = []
, chunk = ''
, l //Declare l here to avoid accidental global var declaration
, zone = null
, rule = null;
var lines = str.split('\n')
, arr = []
, chunk = ''
, l
, zone = null
, rule = null;
for (var i = 0; i < lines.length; i++) {

@@ -843,20 +854,24 @@ l = lines[i];

chunk = arr.shift();
// Ignore Leap
//Ignore Leap.
switch (chunk) {
case 'Zone':
zone = arr.shift();
if (!_this.zones[zone]) { _this.zones[zone] = [] }
_this.zones[zone].push(arr);
if (!_this.zones[zone]) {
_this.zones[zone] = [];
}
_this.zones[zone].push(arr);
break;
case 'Rule':
rule = arr.shift();
if (!_this.rules[rule]) { _this.rules[rule] = [] }
_this.rules[rule].push(arr);
if (!_this.rules[rule]) {
_this.rules[rule] = [];
}
_this.rules[rule].push(arr);
break;
case 'Link':
// No zones for these should already exist
//No zones for these should already exist.
if (_this.zones[arr[1]]) {
throw new Error('Error with Link ' + arr[1] + '. Cannot create link of a preexisted zone.');
}
// Create the link
//Create the link.
_this.zones[arr[1]] = arr[0];

@@ -867,9 +882,10 @@ break;

}
return true;
};
// Expose transport mechanism and allow overwrite
//Expose transport mechanism and allow overwrite.
this.transport = _transport;
this.getTzInfo = function (dt, tz, isUTC) {
// Lazy-load any zones not yet loaded
//Lazy-load any zones not yet loaded.
if (this.loadingScheme === this.loadingSchemes.LAZY_LOAD) {
// Get the correct region for the zone
//Get the correct region for the zone.
var zoneFile = getRegionForTimezone(tz);

@@ -880,4 +896,4 @@ if (!zoneFile) {

if (!this.loadedZones[zoneFile]) {
// Get the file and parse it -- use synchronous XHR
this.loadZoneFile(zoneFile, true);
//Get the file and parse it -- use synchronous XHR.
this.loadZoneFile(zoneFile);
}

@@ -887,3 +903,3 @@ }

var off = getBasicOffset(zone);
// See if the offset needs adjustment
//See if the offset needs adjustment.
var rule = getRule(dt, zone, isUTC);

@@ -896,3 +912,3 @@ if (rule) {

};
}
};
}).call(this);

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc