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.3 to 0.4.4

spec/tz.manual.spec.js

6

package.json

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

"description": "JavaScript timezone library based on Olson timezone data",
"version": "0.4.3",
"version": "0.4.4",
"main": "src/date.js",

@@ -22,6 +22,6 @@ "homepage": "https://github.com/mde/timezone-js",

"scripts": {
"test": "jake test:init; jake test"
"test": "./node_modules/jake/bin/cli.js test:cli"
},
"engines": {
"node": "~0.6.0"
"node": "~0.8.0"
},

@@ -28,0 +28,0 @@ "dependencies": {},

# TimezoneJS.Date
[![Build Status](https://secure.travis-ci.org/mde/timezone-js.png)](https://secure.travis-ci.org/mde/timezone-js)
A timezone-enabled, drop-in replacement for the stock JavaScript Date. The `timezoneJS.Date` object is API-compatible with JS Date, with the same getter and setter methods -- it should work fine in any code that works with normal JavaScript Dates.

@@ -23,2 +25,20 @@

Here is an example of how to get the Olson time zone files:
##!/bin/bash
# NOTE: Run from your webroot
# Create the /tz directory
mkdir tz
# Download the latest Olson files
curl ftp://ftp.iana.org/tz/tzdata-latest.tar.gz -o tz/tzdata-latest.tar.gz
# Expand the files
tar -xvzf tz/tzdata-latest.tar.gz -C tz
# Optionally, you can remove the downloaded archives.
rm tz/tzdata-latest.tar.gz
Then you'll need to make the files available to the `timezoneJS.timezone` code, and initialize the code to parse your default region. (This will be North America if you don't change it). No sense in downloading and parsing timezone data for the entire world if you're not going to be using it.

@@ -153,2 +173,22 @@

Feel free to fork and modify at your own will.
The source code is annotated and doc can be generated with `jake doc`.
The source code is annotated and doc can be generated with `jake doc`.
## License
Copyright 2010 Matthew Eernisse (mde@fleegix.org) and Open Source Applications Foundation.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Credits: Ideas included from incomplete JS implementation of Olson parser, "XMLDAte" by Philippe Goetz (philippe.goetz@wanadoo.fr)
Contributions:
- Jan Niehusmann
- Ricky Romero
- Preston Hunt (prestonhunt@gmail.com)
- Dov. B Katz (dov.katz@morganstanley.com)
- Peter Bergström (pbergstr@mac.com)
- Long Ho (@longlho)
var TestUtils = require('./test-utils')
, timezoneJS = TestUtils.getTimezoneJS();
, timezoneJS = TestUtils.getTimezoneJS();

@@ -16,3 +16,3 @@ describe('timezoneJS.Date', function () {

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,'Etc/UTC');
var date = new timezoneJS.Date(2011, 9, 28, 12, 44, 22, 172,'Etc/UTC');
expect(date.getTime()).toEqual(1319805862172);

@@ -43,8 +43,14 @@ expect(date.toString()).toEqual('2011-10-28 12:44:22');

it('should use a default format with the given tz', function () {
var date = new timezoneJS.Date(2012, 7, 30, 10, 56, 0, 0, 'America/Los_Angeles');
expect(date.toString(null, 'Etc/UTC')).toEqual(date.toString('yyyy-MM-dd HH:mm:ss', 'Etc/UTC'));
expect(date.toString(null, 'America/New_York')).toEqual(date.toString('yyyy-MM-dd HH:mm:ss', 'America/New_York'));
});
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);
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);
});

@@ -78,3 +84,3 @@

var dtA = new Date()
, dt = new timezoneJS.Date();
, dt = new timezoneJS.Date();

@@ -88,3 +94,3 @@ dtA.setTime(dtA.getTime());

var dtA = new Date()
, dt = new timezoneJS.Date();
, dt = new timezoneJS.Date();

@@ -99,3 +105,3 @@ dtA.setTime(dtA.getTime());

var dtA = new Date()
, dt = new timezoneJS.Date();
, dt = new timezoneJS.Date();

@@ -109,3 +115,3 @@ dtA.setTime(dtA.getTime());

var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA.getTime());
, dt = new timezoneJS.Date(dtA.getTime());

@@ -118,3 +124,3 @@ expect(dt.getTime()).toEqual(dtA.getTime());

var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA);
, dt = new timezoneJS.Date(dtA);

@@ -127,5 +133,5 @@ expect(dt.getTime()).toEqual(dtA.getTime());

var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA.getTime(), 'Asia/Bangkok');
, dt = new timezoneJS.Date(dtA.getTime(), 'Asia/Bangkok');
expect(dt.getTime()).toEqual(-7 * 3600 * 1000);
expect(dt.getTime()).toEqual(0);
});

@@ -135,13 +141,14 @@

var dtA = new Date(0)
, dt = new timezoneJS.Date(dtA, 'Asia/Bangkok');
, dt = new timezoneJS.Date(dtA, 'Asia/Bangkok');
expect(dt.getTime()).toEqual(-7 * 3600 * 1000);
expect(dt.getTime()).toEqual(0);
});
it('should take in String and Asia/Bangkok as constructor', function () {
//This is a RFC 3339 UTC string format
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');
expect(dt.toString()).toEqual('2012-01-01 22:00:00');
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-01T22:00:00.000');
});

@@ -159,3 +166,3 @@

var dtA = new Date()
, dt = new timezoneJS.Date(dtA.toJSON());
, dt = new timezoneJS.Date(dtA.toJSON());

@@ -168,3 +175,3 @@ expect(dt.toJSON()).toEqual(dtA.toJSON());

var dtA = new Date(0)
, dt = new timezoneJS.Date(0, 'Etc/UTC');
, dt = new timezoneJS.Date(0, 'Etc/UTC');

@@ -177,3 +184,3 @@ dt.setHours(6);

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');
, dt2 = new timezoneJS.Date(2011, 4, 15, 23, 0, 0, 0, 'Asia/Bangkok');

@@ -199,5 +206,6 @@ var hours = dt.getHours();

it('should adjust daylight saving correctly', function () {
var dt1 = new timezoneJS.Date('2012-03-11T03:00:00', 'America/Chicago');
var dt1 = new timezoneJS.Date(2012, 2, 11, 3, 0, 0, 'America/Chicago');
expect(dt1.getTimezoneAbbreviation()).toEqual('CDT');
var dt2 = new timezoneJS.Date('2012-03-11T01:59:59', 'America/Chicago');
expect(dt1.getTimezoneOffset()).toEqual(300);
var dt2 = new timezoneJS.Date(2012, 2, 11, 1, 59, 59, 'America/Chicago');

@@ -210,3 +218,3 @@ expect(dt2.getTimezoneAbbreviation()).toEqual('CST');

var dt = new timezoneJS.Date(0, 'America/Chicago')
, dtA = dt.clone();
, dtA = dt.clone();

@@ -219,3 +227,25 @@ expect(dt.getTime()).toEqual(dtA.getTime());

it('should convert timezone quickly', function () {
var start = Date.now()
, yearToMillis = 5 * 365 * 24 * 3600 * 1000
, date;
for (var i = 0; i < 5000; i++) {
date = new timezoneJS.Date(start - Math.random() * yearToMillis, 'America/New_York');
date.setTimezone('Europe/Minsk');
}
console.log('Took ' + (Date.now() - start) + 'ms to convert 5000 dates');
});
it('should output 1955-10-30 00:00:00 America/New_York as EDT', function () {
var dt = new timezoneJS.Date(1955, 9, 30, 0, 0, 0, 'America/New_York');
expect(dt.getTimezoneOffset()).toEqual(240);
});
it('should handle Pacific/Apia correctly', function () {
var dt = new timezoneJS.Date(2011, 11, 29, 23, 59, 59, 'Pacific/Apia');
var t = dt.getTime() + 1000;
dt.setTime(t);
expect(dt.toString()).toEqual('2011-12-31 00:00:00');
expect(dt.getTime()).toEqual(t);
});
});
var fs = require('fs');
(function () {
var root = this;

@@ -21,9 +20,3 @@

}
//Reset everything
timezoneJS.timezone.zones = {};
timezoneJS.timezone.rules = {};
timezoneJS.timezone.loadedZones = {};
//Set up again
timezoneJS.timezone.zoneFileBasePath = 'lib/tz';
timezoneJS.timezone.transport = function (opts) {

@@ -40,4 +33,10 @@ // No success handler, what's the point?

};
timezoneJS.timezone.loadingScheme = opts.loadingScheme;
timezoneJS.timezone.init(opts);
if (opts.loadingScheme !== timezoneJS.timezone.loadingSchemes.MANUAL_LOAD) {
//Set up again
timezoneJS.timezone.zoneFileBasePath = 'lib/tz';
timezoneJS.timezone.init(opts);
}
return timezoneJS;

@@ -47,2 +46,8 @@ };

TestUtils.getTimezoneJS = function (options) {
//Delete date.js from require cache to force it to reload
for (var k in require.cache) {
if (k.indexOf('date.js') > -1) {
delete require.cache[k];
}
}
return init(require('../src/date'), options);

@@ -49,0 +54,0 @@ }

@@ -45,2 +45,26 @@ var TestUtils = require('./test-utils')

it('should get New_York time correctly', function () {
// Source: http://www.timeanddate.com/worldclock/city.html?n=179
// Changes every year!
var dt;
// 2006
dt = timezoneJS.timezone.getTzInfo(parseISO('2006-04-02T01:59:59'), 'America/New_York');
expect(dt.tzOffset).toEqual(300);
dt = timezoneJS.timezone.getTzInfo(parseISO('2006-04-02T03:00:01'), 'America/New_York');
expect(dt.tzOffset).toEqual(240);
dt = timezoneJS.timezone.getTzInfo(parseISO('2006-10-29T00:59:59'), 'America/New_York');
expect(dt.tzOffset).toEqual(240);
dt = timezoneJS.timezone.getTzInfo(parseISO('2006-10-29T03:00:01'), 'America/New_York');
expect(dt.tzOffset).toEqual(300);
// 2009
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-03-08T01:59:59'), 'America/New_York');
expect(dt.tzOffset).toEqual(300);
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-03-08T03:00:01'), 'America/New_York');
expect(dt.tzOffset).toEqual(240);
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-11-01T00:59:59'), 'America/New_York');
expect(dt.tzOffset).toEqual(240);
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-11-01T03:00:01'), 'America/New_York');
expect(dt.tzOffset).toEqual(300);
});
it('should get Jerusalem time correctly', function () {

@@ -138,2 +162,17 @@ // Source: http://www.timeanddate.com/worldclock/city.html?n=110

it('should get tzInfo quickly', function () {
var time = Date.now();
for (var i = 0; i < 5000; i++) {
timezoneJS.timezone.getTzInfo(new Date(), 'America/Chicago');
}
console.log('Took ' + (Date.now() - time) + 'ms to get 5000 same tzInfo');
});
it('should throw error with invalid zone', function () {
var testFn = function () {
timezoneJS.timezone.getTzInfo(new Date(), 'asd')
}
expect(testFn).toThrow(new Error('Timezone "asd" is either incorrect, or not loaded in the timezone registry.'));
});
});

@@ -57,5 +57,30 @@ // -----

// Declare constant list of days and months. Unfortunately this doesn't leave room for i18n due to the Olson data being in English itself
, Days = timezoneJS.Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
, Months = timezoneJS.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
, DAYS = timezoneJS.Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
, MONTHS = timezoneJS.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
, SHORT_MONTHS = {}
, SHORT_DAYS = {}
, EXACT_DATE_TIME = {}
, TZ_REGEXP = new RegExp('^[a-zA-Z]+/');
//`{ "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++) {
SHORT_MONTHS[MONTHS[i].substr(0, 3)] = i;
}
//`{ "Sun": 0, "Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5, "Sat": 6 }`
for (i = 0; i < DAYS.length; i++) {
SHORT_DAYS[DAYS[i].substr(0, 3)] = i;
}
//Handle array indexOf in IE
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (el) {
for (var i = 0; i < this.length; i++ ) {
if (el === this[i]) return i;
}
return -1;
}
}
// Format a number to the length = digits. For ex:

@@ -113,2 +138,3 @@ //

url : opts.url,
dataType: 'text',
method : 'GET',

@@ -146,3 +172,3 @@ error : opts.error,

}
if (typeof args[args.length - 1] === 'string' && /^[a-zA-Z]+\//gi.test(args[args.length - 1])) {
if (typeof args[args.length - 1] === 'string' && TZ_REGEXP.test(args[args.length - 1])) {
tz = args.pop();

@@ -165,5 +191,2 @@ }

this._extractTimeArray = function () {
return [this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.milliseconds, this.timezone];
};
this._useCache = false;

@@ -175,3 +198,3 @@ this._tzInfo = {};

this.date = 0;
this.hours= 0;
this.hours = 0;
this.minutes = 0;

@@ -181,3 +204,2 @@ this.seconds = 0;

this.timezone = tz || null;
this.utc = tz === 'Etc/UTC' || tz === 'Etc/GMT';
//Tricky part:

@@ -187,3 +209,7 @@ // For the cases where there are 1/2 arguments: `timezoneJS.Date(millis, [tz])` and `timezoneJS.Date(Date, [tz])`. The

// is specified. Because if `tz` is not specified, `dt` can be in local time.
this.setFromDateObjProxy(dt, !arr.length && tz);
if (arr.length) {
this.setFromDateObjProxy(dt);
} else {
this.setFromTimeProxy(dt.getTime(), tz);
}
};

@@ -202,6 +228,13 @@

getSeconds: function () { return this.seconds; },
getUTCDate: function () { return this.getUTCDateProxy().getUTCDate(); },
getUTCDay: function () { return this.getUTCDateProxy().getUTCDay(); },
getUTCFullYear: function () { return this.getUTCDateProxy().getUTCFullYear(); },
getUTCHours: function () { return this.getUTCDateProxy().getUTCHours(); },
getUTCMilliseconds: function () { return this.getUTCDateProxy().getUTCMilliseconds(); },
getUTCMinutes: function () { return this.getUTCDateProxy().getUTCMinutes(); },
getUTCMonth: function () { return this.getUTCDateProxy().getUTCMonth(); },
getUTCSeconds: function () { return this.getUTCDateProxy().getUTCSeconds(); },
// Time adjusted to user-specified timezone
getTime: function () {
var dt = Date.UTC.apply(root, this._extractTimeArray());
return dt + (this.getTimezoneOffset() * 60 * 1000);
return this._timeProxy + (this.getTimezoneOffset() * 60 * 1000);
},

@@ -212,4 +245,2 @@ getTimezone: function () { return this.timezone; },

getTimezoneInfo: function () {
// If UTC, easy!
if (this.utc) return { tzOffset: 0, tzAbbr: 'UTC' };
if (this._useCache) return this._tzInfo;

@@ -219,5 +250,5 @@ var res;

if (this.timezone) {
var dt = new Date(Date.UTC.apply(root, this._extractTimeArray()));
var tz = this.timezone;
res = timezoneJS.timezone.getTzInfo(dt, tz);
res = this.timezone === 'Etc/UTC' || this.timezone === 'Etc/GMT'
? { tzOffset: 0, tzAbbr: 'UTC' }
: timezoneJS.timezone.getTzInfo(this._timeProxy, this.timezone);
}

@@ -230,12 +261,9 @@ // If no timezone was specified, use the local browser offset

this._useCache = true;
return res;
return res
},
getUTCDate: function () { return this.getUTCDateProxy().getUTCDate(); },
getUTCDay: function () { return this.getUTCDateProxy().getUTCDay(); },
getUTCFullYear: function () { return this.getUTCDateProxy().getUTCFullYear(); },
getUTCHours: function () { return this.getUTCDateProxy().getUTCHours(); },
getUTCMilliseconds: function () { return this.getUTCDateProxy().getUTCMilliseconds(); },
getUTCMinutes: function () { return this.getUTCDateProxy().getUTCMinutes(); },
getUTCMonth: function () { return this.getUTCDateProxy().getUTCMonth(); },
getUTCSeconds: function () { return this.getUTCDateProxy().getUTCSeconds(); },
getUTCDateProxy: function () {
var dt = new Date(this._timeProxy);
dt.setUTCMinutes(dt.getUTCMinutes() + this.getTimezoneOffset());
return dt;
},
setDate: function (n) { this.setAttribute('date', n); },

@@ -251,5 +279,3 @@ setFullYear: function (n) { this.setAttribute('year', n); },

if (isNaN(n)) { throw new Error('Units must be a number.'); }
var dt = new Date(0);
dt.setUTCMilliseconds(n - (this.getTimezoneOffset() * 60 * 1000));
this.setFromDateObjProxy(dt, true);
this.setFromTimeProxy(n, this.timezone);
},

@@ -263,2 +289,52 @@ setUTCDate: function (n) { this.setUTCAttribute('date', n); },

setUTCSeconds: function (n) { this.setUTCAttribute('seconds', n); },
setFromDateObjProxy: function (dt) {
this.year = dt.getFullYear();
this.month = dt.getMonth();
this.date = dt.getDate();
this.hours = dt.getHours();
this.minutes = dt.getMinutes();
this.seconds = dt.getSeconds();
this.milliseconds = dt.getMilliseconds();
this._day = dt.getDay();
this._dateProxy = dt;
this._timeProxy = Date.UTC(this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.milliseconds);
this._useCache = false;
},
setFromTimeProxy: function (utcMillis, tz) {
var dt = new Date(utcMillis);
var tzOffset;
tzOffset = tz ? timezoneJS.timezone.getTzInfo(dt, tz).tzOffset : dt.getTimezoneOffset();
dt.setTime(utcMillis + (dt.getTimezoneOffset() - tzOffset) * 60000);
this.setFromDateObjProxy(dt);
},
setAttribute: function (unit, n) {
if (isNaN(n)) { throw new Error('Units must be a number.'); }
var dt = this._dateProxy;
var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
dt['set' + meth](n);
this.setFromDateObjProxy(dt);
},
setUTCAttribute: function (unit, n) {
if (isNaN(n)) { throw new Error('Units must be a number.'); }
var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
var dt = this.getUTCDateProxy();
dt['setUTC' + meth](n);
dt.setUTCMinutes(dt.getUTCMinutes() - this.getTimezoneOffset());
this.setFromTimeProxy(dt.getTime() + this.getTimezoneOffset() * 60000, this.timezone);
},
setTimezone: function (tz) {
var previousOffset = this.getTimezoneInfo().tzOffset;
this.timezone = tz;
this._useCache = false;
// Set UTC minutes offsets by the delta of the two timezones
this.setUTCMinutes(this.getUTCMinutes() - this.getTimezoneInfo().tzOffset + previousOffset);
},
removeTimezone: function () {
this.timezone = null;
this._useCache = false;
},
valueOf: function () { return this.getTime(); },
clone: function () {
return this.timezone ? new timezoneJS.Date(this.getTime(), this.timezone) : new timezoneJS.Date(this.getTime());
},
toGMTString: function () { return this.toString('EEE, dd MMM yyyy HH:mm:ss Z', 'Etc/GMT'); },

@@ -274,5 +350,5 @@ toLocaleString: function () {},

// Default format is the same as toISOString
if (!format) return this.toString('yyyy-MM-dd HH:mm:ss');
if (!format) format = 'yyyy-MM-dd HH:mm:ss';
var result = format;
var tzInfo = tz ? timezoneJS.timezone.getTzInfo(new Date(this.getTime()), tz) : this.getTimezoneInfo();
var tzInfo = tz ? timezoneJS.timezone.getTzInfo(this.getTime(), tz) : this.getTimezoneInfo();
var _this = this;

@@ -322,3 +398,3 @@ // If timezone is specified, get a clone of the current Date object and modify it

// `E`: day
.replace(/E+/g, function (token) { return timezoneJS.Days[_this.getDay()].substring(0, token.length); })
.replace(/E+/g, function (token) { return DAYS[_this.getDay()].substring(0, token.length); })
// `Z`: timezone abbreviation

@@ -328,55 +404,2 @@ .replace(/Z+/gi, function () { return tzInfo.tzAbbr; });

toUTCString: function () { return this.toGMTString(); },
valueOf: function () { return this.getTime(); },
clone: function () {
return new timezoneJS.Date(this._extractTimeArray());
},
setFromDateObjProxy: function (dt, fromUTC) {
this.year = fromUTC ? dt.getUTCFullYear() : dt.getFullYear();
this.month = fromUTC ? dt.getUTCMonth() : dt.getMonth();
this.date = fromUTC ? dt.getUTCDate() : dt.getDate();
this.hours = fromUTC ? dt.getUTCHours() : dt.getHours();
this.minutes = fromUTC ? dt.getUTCMinutes() : dt.getMinutes();
this.seconds = fromUTC ? dt.getUTCSeconds() : dt.getSeconds();
this.milliseconds = fromUTC ? dt.getUTCMilliseconds() : dt.getMilliseconds();
this._day = fromUTC ? dt.getUTCDay() : dt.getDay();
this._dateProxy = dt;
this._useCache = false;
},
getUTCDateProxy: function () {
var dt = new Date(Date.UTC.apply(root, this._extractTimeArray()));
dt.setUTCMinutes(dt.getUTCMinutes() + this.getTimezoneOffset());
return dt;
},
setAttribute: function (unit, n) {
if (isNaN(n)) { throw new Error('Units must be a number.'); }
var dt = this._dateProxy;
var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
dt['set' + meth](n);
this.setFromDateObjProxy(dt);
},
setUTCAttribute: function (unit, n) {
if (isNaN(n)) { throw new Error('Units must be a number.'); }
var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
var dt = this.getUTCDateProxy();
dt['setUTC' + meth](n);
dt.setUTCMinutes(dt.getUTCMinutes() - this.getTimezoneOffset());
this.setFromDateObjProxy(dt, true);
},
setTimezone: function (tz) {
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);
},
removeTimezone: function () {
this.utc = false;
this.timezone = null;
this._useCache = false;
},
civilToJulianDayNumber: function (y, m, d) {

@@ -408,17 +431,4 @@ var a;

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 }`
for (var i = 0; i < Months.length; i++) {
monthMap[Months[i].substr(0,3).toLowerCase()] = 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;
}
, regionMap = {'Etc':'etcetera','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 = {'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'};
function invalidTZError(t) { throw new Error('Timezone "' + t + '" is either incorrect, or not loaded in the timezone registry.'); }

@@ -470,8 +480,23 @@ function builtInLoadZoneFile(fileName, opts) {

hms[3] = hms[3] ? parseInt(hms[3], 10) : 0;
return hms;
}
function processZone(z) {
if (!z[3]) { return; }
var yea = parseInt(z[3], 10);
var mon = 11;
var dat = 31;
if (z[4]) {
mon = SHORT_MONTHS[z[4].substr(0, 3)];
dat = parseInt(z[5], 10) || 1;
}
var string = z[6] ? z[6] : '00:00:00'
, t = parseTimeString(string);
return [yea, mon, dat, t[1], t[2], t[3]];
}
function getZone(dt, tz) {
var utcMillis = typeof dt === 'number' ? dt : new Date(dt).getTime();
var t = tz;
var zoneList = _this.zones[t];
// Follow links to get to an acutal zone
// Follow links to get to an actual zone
while (typeof zoneList === "string") {

@@ -493,25 +518,17 @@ t = zoneList;

}
for (var i = 0; i < zoneList.length; i++) {
if (zoneList.length === 0) {
throw new Error('No Zone found for "' + tz + '" on ' + dt);
}
//Do backwards lookup since most use cases deal with newer dates.
for (var i = zoneList.length - 1; i >= 0; i--) {
var z = zoneList[i];
if (!z[3]) { break; }
var yea = parseInt(z[3], 10);
var mon = 11;
var dat = 31;
if (z[4]) {
mon = monthMap[z[4].substr(0, 3).toLowerCase()];
dat = parseInt(z[5], 10);
}
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 (z[3] && utcMillis > z[3]) break;
}
if (i === zoneList.length) { throw new Error('No Zone found for "' + tz + '" on ' + dt); }
return zoneList[i];
return zoneList[i+1];
}
function getBasicOffset(z) {
var off = parseTimeString(z[0])
, adj = z[0].indexOf('-') === 0 ? -1 : 1;
function getBasicOffset(time) {
var off = parseTimeString(time)
, adj = time.indexOf('-') === 0 ? -1 : 1;
off = adj * (((off[1] * 60 + off[2]) * 60 + off[3]) * 1000);
return -off/60/1000;
return off/60/1000;
}

@@ -521,5 +538,6 @@

// in local time (ie. date.getUTC*() returns local time components)
function getRule(date, zone, isUTC) {
function getRule(dt, zone, isUTC) {
var date = typeof dt === 'number' ? new Date(dt) : dt;
var ruleset = zone[1];
var basicOffset = getBasicOffset(zone);
var basicOffset = zone[0];

@@ -533,3 +551,3 @@ //Convert a date to UTC. Depending on the 'type' parameter, the date

//
// - `w`: wall clock time (adjust for both time zone and DST offset).
// - `w`: wall clock time (adjust for both time zone and DST offset).
//

@@ -545,5 +563,5 @@ // DST adjustment is done using the rule given as third argument.

} else if (type === 'w' || !type) { // Wall Clock Time
offset = getAdjustedOffset(basicOffset,rule);
offset = getAdjustedOffset(basicOffset, rule);
} else {
throw("unknown type "+type);
throw("unknown type " + type);
}

@@ -571,52 +589,51 @@ offset *= 60 * 1000; // to millis

var year = yearAndRule[0]
, rule = yearAndRule[1]
, months = {} // Assume that the rule applies to the year of the given date.
, days = {};
, rule = yearAndRule[1];
// Assume that the rule applies to the year of the given date.
//{ "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++) {
months[Months[i].substr(0, 3)] = i;
}
var hms = rule[5];
var effectiveDate;
//{ "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;
}
if (!EXACT_DATE_TIME[year])
EXACT_DATE_TIME[year] = {};
var hms = parseTimeString(rule[5]);
var effectiveDate;
//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));
}
//Let's hunt for the date.
// Result for given parameters is already stored
if (EXACT_DATE_TIME[year][rule])
effectiveDate = EXACT_DATE_TIME[year][rule];
else {
var targetDay
, operator;
//Example: `lastThu`
if (rule[4].substr(0, 4) === "last") {
// Start at the last day of the month and work backward.
effectiveDate = new Date(Date.UTC(year, months[rule[3]] + 1, 1, hms[1] - 24, hms[2], hms[3], 0));
targetDay = days[rule[4].substr(4, 3).toLowerCase()];
operator = "<=";
//If we have a specific date, use that!
if (!isNaN(rule[4])) {
effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4], hms[1], hms[2], hms[3], 0));
}
//Example: `Sun>=15`
//Let's hunt for the date.
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));
targetDay = days[rule[4].substr(0, 3).toLowerCase()];
operator = rule[4].substr(3, 2);
var targetDay
, operator;
//Example: `lastThu`
if (rule[4].substr(0, 4) === "last") {
// Start at the last day of the month and work backward.
effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]] + 1, 1, hms[1] - 24, hms[2], hms[3], 0));
targetDay = SHORT_DAYS[rule[4].substr(4, 3)];
operator = "<=";
}
//Example: `Sun>=15`
else {
//Start at the specified date.
effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4].substr(5), hms[1], hms[2], hms[3], 0));
targetDay = SHORT_DAYS[rule[4].substr(0, 3)];
operator = rule[4].substr(3, 2);
}
var ourDay = effectiveDate.getUTCDay();
//Go forwards.
if (operator === ">=") {
effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay + ((targetDay < ourDay) ? 7 : 0)));
}
//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)));
}
}
var ourDay = effectiveDate.getUTCDay();
//Go forwards.
if (operator === ">=") {
effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay + ((targetDay < ourDay) ? 7 : 0)));
}
//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)));
}
EXACT_DATE_TIME[year][rule] = effectiveDate;
}
//If previous rule is given, correct for the fact that the starting time of the current

@@ -634,8 +651,8 @@ // rule may be specified in local time.

//Exclude future rules.
if (Number(ruleset[i][0]) <= year &&
if (ruleset[i][0] <= year &&
(
// Date is in a set range.
Number(ruleset[i][1]) >= year ||
ruleset[i][1] >= year ||
// Date is in an "only" year.
(Number(ruleset[i][0]) === year && ruleset[i][1] === "only") ||
(ruleset[i][0] === year && ruleset[i][1] === "only") ||
//We're in a range from the start year to infinity.

@@ -655,4 +672,9 @@ ruleset[i][1] === "max"

var compareDates = function (a, b, prev) {
var year, rule;
if (a.constructor !== Date) {
a = convertRuleToExactDateAndTime(a, prev);
year = a[0];
rule = a[1];
a = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule])
? EXACT_DATE_TIME[year][rule]
: convertRuleToExactDateAndTime(a, prev);
} else if (prev) {

@@ -662,3 +684,6 @@ a = convertDateToUTC(a, isUTC ? 'u' : 'w', prev);

if (b.constructor !== Date) {
b = convertRuleToExactDateAndTime(b, prev);
year = b[0];
rule = b[1];
b = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule]) ? EXACT_DATE_TIME[year][rule]
: convertRuleToExactDateAndTime(b, prev);
} else if (prev) {

@@ -689,3 +714,2 @@ b = convertDateToUTC(b, isUTC ? 'u' : 'w', prev);

}
var pinpoint = applicableRules.indexOf(date);

@@ -696,2 +720,3 @@ if (pinpoint > 1 && compareDates(date, applicableRules[pinpoint-1], applicableRules[pinpoint-2][1]) < 0) {

} 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.

@@ -706,10 +731,3 @@ return applicableRules[pinpoint + 1][1];

function getAdjustedOffset(off, rule) {
var save = rule[6];
var t = parseTimeString(save);
var adj = save.indexOf('-') === 0 ? -1 : 1;
var ret = (adj*(((t[1] *60 + t[2]) * 60 + t[3]) * 1000));
ret = ret/60/1000;
ret -= off;
ret = -Math.ceil(ret);
return ret;
return -Math.ceil(rule[6] - off);
}

@@ -734,5 +752,3 @@ function getAbbreviation(zone, rule) {

//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];
res = base.split("/", 2)[rule[6] ? 1 : 0];
} else {

@@ -847,2 +863,7 @@ res = base;

}
if (arr.length < 3) break;
//Process zone right here and replace 3rd element with the processed array.
arr.splice(3, arr.length, processZone(arr));
if (arr[3]) arr[3] = Date.UTC.apply(null, arr[3]);
arr[0] = -getBasicOffset(arr[0]);
_this.zones[zone].push(arr);

@@ -855,2 +876,9 @@ break;

}
//Parse int FROM year and TO year
arr[0] = parseInt(arr[0], 10);
arr[1] = parseInt(arr[1], 10) || arr[1];
//Parse time string AT
arr[5] = parseTimeString(arr[5]);
//Parse offset SAVE
arr[6] = getBasicOffset(arr[6]);
_this.rules[rule].push(arr);

@@ -886,10 +914,10 @@ break;

}
var zone = getZone(dt, tz);
var off = getBasicOffset(zone);
var z = getZone(dt, tz);
var off = z[0];
//See if the offset needs adjustment.
var rule = getRule(dt, zone, isUTC);
var rule = getRule(dt, z, isUTC);
if (rule) {
off = getAdjustedOffset(off, rule);
}
var abbr = getAbbreviation(zone, rule);
var abbr = getAbbreviation(z, rule);
return { tzOffset: off, tzAbbr: abbr };

@@ -896,0 +924,0 @@ };

(function () {
var fs = require('fs')
, timezoneJS = require('./date');
, timezoneJS = require('./date')
, EXCLUDED = new RegExp('Makefile|factory|(\\.+)', 'i');

@@ -24,2 +25,3 @@ function parse(args) {

var zoneFile = _tz.zoneFiles[i];
if (EXCLUDED.test(zoneFile)) continue;
var zoneData = fs.readFileSync(baseDir + '/' + zoneFile, 'utf8');

@@ -26,0 +28,0 @@ _tz.parseZones(zoneData);

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