new timezone handling with timezoneJS.date.js

Does not work with DST yet... Maybe rewrite the js date/timehandling in php....

Status: does not work as expected!
This commit is contained in:
2013-02-26 23:32:02 +00:00
parent 5af208a20f
commit 270edc7ee5
42 changed files with 20618 additions and 11 deletions

87
js/timezone-js/Jakefile Normal file
View File

@@ -0,0 +1,87 @@
var fs = require('fs')
, path = require('path');
namespace('test', function () {
desc('Sets up tests by downloading the timezone data.');
task('init', ['updateTzData'], function () {
complete();
}, {async: true});
task('clobberTzData', function () {
console.log('Removing old timezone data.');
jake.rmRf('lib/tz');
});
desc('Downloads the newest timezone data.');
task('updateTzData', ['clobberTzData'], function () {
var cmds = [
'echo "Downloading new timezone data ..."'
, 'curl ftp://ftp.iana.org/tz/tzdata-latest.tar.gz ' +
'-o lib/tz/tzdata-latest.tar.gz'
, 'echo "Expanding archive ..."'
, 'tar -xvzf lib/tz/tzdata-latest.tar.gz -C lib/tz'
];
jake.mkdirP('lib/tz');
jake.exec(cmds, function () {
console.log('Retrieved new timezone data');
console.log('Parsing tz...');
jake.exec('node src/node-preparse.js lib/tz > lib/all_cities.json', function () {
console.log('Done parsing tz');
complete();
}, {printStdout: true, printStderr: true});
}, {printStdout: true});
}, {async: true});
task('run', function () {
//Comply to 0.8.0 and 0.6.x
var existsSync = fs.existsSync || path.existsSync;
if (!existsSync('lib/tz')) {
fail('No timezone data. Please run "jake test:init".');
}
jake.exec(['jasmine-node spec'], function () {
complete();
}, {printStdout: true});
}, {async: true});
task('cli', ['init', 'run']);
});
desc('Runs the tests.');
task('test', ['test:run'], function () {});
namespace('doc', function () {
task('generate', ['doc:clobber'], function () {
var cmd = 'docco src/date.js';
console.log('Generating docs ...');
jake.exec([cmd], function () {
console.log('Done.');
complete();
});
}, {async: true});
task('clobber', function () {
var cmd = 'rm -fr ./docs';
jake.exec([cmd], function () {
console.log('Clobbered old docs.');
complete();
});
}, {async: true});
});
desc('Generates docs.');
task('doc', ['doc:generate']);
var p = new jake.NpmPublishTask('timezone-js', [
'Jakefile'
, 'README.md'
, 'package.json'
, 'spec/*'
, 'src/*'
]);
jake.Task['npm:definePackage'].invoke();

192
js/timezone-js/README.md Normal file
View File

@@ -0,0 +1,192 @@
# 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.
[Mailing list](http://groups.google.com/group/timezone-js)
## Overview
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.
The constructor function and setter methods use proxy JavaScript Date objects behind the scenes, so you can use strings like '10/22/2006' with the constructor. You also get the same sensible wraparound behavior with numeric parameters (like setting a value of 14 for the month wraps around to the next March).
The other significant difference from the built-in JavaScript Date is that `timezoneJS.Date` also has named properties that store the values of year, month, date, etc., so it can be directly serialized to JSON and used for data transfer.
## Setup
First you'll need to include the code on your page. Both `timezoneJS.Date`, and the supporting code it needs in `timezoneJS.timezone` are bundled in the `date.js` file in `src` directory. Include the code on your page with a normal JavaScript script include, like so:
<script type="text/javascript" src="/js/timezone-js/src/date.js">
Next you'll need the Olson time zone files -- `timezoneJS.Date` uses the raw Olson data to calculate timezone offsets. The Olson region files are simple, structured text data, which download quickly and parse easily. (They also compress to a very small size.)
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.
Put your directory of Olson files somewhere under your Web server root, and point `timezoneJS.timezone.zoneFileBasePath` to it. Then call the init function. Your code will look something like this:
timezoneJS.timezone.zoneFileBasePath = '/tz';
timezoneJS.timezone.init();
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.
## Usage
Create a `timezoneJS.Date` the same way as a normal JavaScript Date, but append a timezone parameter on the end:
var dt = new timezoneJS.Date('10/31/2008', 'America/New_York');
var dt = new timezoneJS.Date(2008, 9, 31, 11, 45, 'America/Los_Angeles');
Naturally enough, the `getTimezoneOffset` method returns the timezone offset in minutes based on the timezone you set for the date.
// Pre-DST-leap
var dt = new timezoneJS.Date(2006, 9, 29, 1, 59, 'America/Los_Angeles');
dt.getTimezoneOffset(); => 420
// Post-DST-leap
var dt = new timezoneJS.Date(2006, 9, 29, 2, 0, 'America/Los_Angeles');
dt.getTimezoneOffset(); => 480
Just as you'd expect, the getTime method gives you the UTC timestamp for the given date:
var dtA = new timezoneJS.Date(2007, 9, 31, 10, 30, 'America/Los_Angeles');
var dtB = new timezoneJS.Date(2007, 9, 31, 12, 30, 'America/Chicago');
// Same timestamp
dtA.getTime(); => 1193855400000
dtB.getTime(); => 1193855400000
You can set (or reset) the timezone using the `setTimezone` method:
var dt = new timezoneJS.Date('10/31/2006', 'America/Juneau');
dt.getTimezoneOffset(); => 540
dt.setTimezone('America/Chicago');
dt.getTimezoneOffset(); => 300
dt.setTimezone('Pacific/Honolulu');
dt.getTimezoneOffset(); => 600
The getTimezone method tells you what timezone a `timezoneJS.Date` is set to.
var dt = new timezoneJS.Date('12/27/2010', 'Asia/Tokyo');
dt.getTimezone(); => 'Asia/Tokyo'
## Customizing
If you don't change it, the timezone region that loads on
initialization is North America (the Olson 'northamerica' file). To change that to another reqion, set `timezoneJS.timezone.defaultZoneFile` to your desired region, like so:
timezoneJS.timezone.zoneFileBasePath = '/tz';
timezoneJS.timezone.defaultZoneFile = 'asia';
timezoneJS.timezone.init();
If you want to preload multiple regions, set it to an array, like this:
timezoneJS.timezone.zoneFileBasePath = '/tz';
timezoneJS.timezone.defaultZoneFile = ['asia', 'backward', 'northamerica', 'southamerica'];
timezoneJS.timezone.init();
By default the `timezoneJS.Date` timezone code lazy-loads the timezone data files, pulling them down and parsing them only as needed.
For example, if you go with the out-of-the-box setup, you'll have all the North American timezones pre-loaded -- but if you were to add a date with a timezone of 'Asia/Seoul,' it would grab the 'asia' Olson file and parse it before calculating the timezone offset for that date.
You can change this behavior by changing the value of `timezoneJS.timezone.loadingScheme`. The three possible values are:
1. `timezoneJS.timezone.loadingSchemes.PRELOAD_ALL` -- this will preload all the timezone data files for all reqions up front. This setting would only make sense if you know your users will be using timezones from all around the world, and you prefer taking the up-front load time to the small on-the-fly lag from lazy loading.
2. `timezoneJS.timezone.loadingSchemes.LAZY_LOAD` -- the default. Loads some amount of data up front, then lazy-loads any other needed timezone data as needed.
3. `timezoneJS.timezone.loadingSchemes.MANUAL_LOAD` -- Preloads no data, and does no lazy loading. Use this setting if you're loading pre-parsed JSON timezone data.
## Pre-Parsed JSON Data
If you know beforehand what specific cities your users are going to be using, you can reduce load times specifically by creating a pre-parsed JSON data file containing only the timezone info for those specific cities.
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:
rhino preparse.js zoneFileDirectory [exemplarCities] > outputfile.json
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.
rhino preparse.js olson_files \
"Asia/Tokyo, America/New_York, Europe/London" \
> major_cities.json
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:
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneJSONData('/major_cities.json', true);
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.
## Compressing
The Olson timezone data files are simple, space- and linefeed-delimited data. The abundance of whitespace means they compress very, very well.
If you plan to use `timezoneJS.Date` in a production Web app, it's highly recommended that you first strip the copious comments found in every Olson file, and serve compressed versions of the files to all browsers that can handle it. **(Note that IE6 reports itself as able to work with gzipped data, but has numerous problems with it.)**
Just to give you an idea of the difference -- merely stripping out the comments from the 'northamerica' file reduces its size by two-thirds -- from 103K to 32K. Gzipping the stripped file reduces it down to 6.5K -- probably smaller than most of the graphics in your app.
The `src` directory has a sample Ruby script that you can use to strip comments from Olson data files.
## 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 `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)

1894
js/timezone-js/fleegix.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
{
"author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
"contributors": [
"Jan Niehusmann",
"Ricky Romero",
"Preston Hunt <prestonhunt@gmail.com>",
"Dov. B Katz <dov.katz@morganstanley.com>",
"Peter Bergström <pbergstr@mac.com>",
"Long Ho <holevietlong@gmail.com> (http://www.longlho.me)"
],
"name": "timezone-js",
"description": "JavaScript timezone library based on Olson timezone data",
"version": "0.4.4",
"main": "src/date.js",
"homepage": "https://github.com/mde/timezone-js",
"repository": {
"type": "git",
"url": "git://github.com/mde/timezone-js.git"
},
"scripts": {
"test": "./node_modules/jake/bin/cli.js test:cli"
},
"engines": {
"node": "~0.8.0"
},
"dependencies": {},
"devDependencies": {
"jake": "latest",
"jasmine-node": "latest"
}
}

View File

@@ -0,0 +1,466 @@
var TestUtils = require('./test-utils')
, timezoneJS = TestUtils.getTimezoneJS();
describe('timezoneJS.Date', function () {
it('should have correct format when initialized', function () {
var date = new timezoneJS.Date();
expect(date.toString()).toMatch(/[\d]{4}(-[\d]{2}){2} ([\d]{2}:){2}[\d]{2}/);
});
it('should format string correctly in toISOString', function () {
var date = new timezoneJS.Date();
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,'Etc/UTC');
expect(date.getTime()).toEqual(1319805862172);
expect(date.toString()).toEqual('2011-10-28 12:44:22');
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,'Etc/UTC');
expect(date.toString('MMM dd yyyy')).toEqual('Oct 28 2011');
expect(date.toString('MMM dd yyyy HH:mm:ss k')).toEqual('Oct 28 2011 12:44:22 PM');
expect(date.toString('MMM dd yyyy HH:mm:ss k Z')).toEqual('Oct 28 2011 12:44:22 PM UTC');
});
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,'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/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,'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', 'Indian/Cocos')).toEqual('Feb 28 2011 07:14:22 PM CCT');
});
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);
});
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(0);
});
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(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 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');
});
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, 2, 11, 3, 0, 0, 'America/Chicago');
expect(dt1.getTimezoneAbbreviation()).toEqual('CDT');
expect(dt1.getTimezoneOffset()).toEqual(300);
var dt2 = new timezoneJS.Date(2012, 2, 11, 1, 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());
});
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);
});
// Years
it("accepts an optional parameter for month in setUTCFullYear", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCMonth()).toEqual(11);
expect(date.getUTCDate()).toEqual(31);
date.setUTCFullYear(2012, 1);
//Febuary does not have a 31st, thus we should wrap to march
expect(date.getUTCMonth()).toEqual(2);
expect(date.getUTCDate()).toEqual(2);
});
it("accepts a second optional parameter for date in setUTCFullYear", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCMonth()).toEqual(11);
expect(date.getUTCDate()).toEqual(31);
date.setUTCFullYear(2012, 1, 1);
//Do not wrap to March because we are setting the date as well
expect(date.getUTCMonth()).toEqual(1);
expect(date.getUTCDate()).toEqual(1);
});
it("accepts an optional parameter for month in setFullYear", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getMonth()).toEqual(11);
expect(date.getDate()).toEqual(31);
date.setFullYear(2012, 1);
//Febuary does not have a 31st, thus we should wrap to march
expect(date.getMonth()).toEqual(2);
expect(date.getDate()).toEqual(2);
});
it("accepts a second optional parameter for date in setFullYear", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getMonth()).toEqual(11);
expect(date.getDate()).toEqual(31);
date.setFullYear(2012, 1, 1);
//Do not wrap to March because we are setting the date as well
expect(date.getMonth()).toEqual(1);
expect(date.getDate()).toEqual(1);
});
// Months
it("accepts an optional parameter for date in setUTCMonths", function() {
var date = new timezoneJS.Date(2000, 7, 14, 0, 0, 0, "Etc/UTC");
expect(date.getUTCMonth()).toEqual(7);
expect(date.getUTCDate()).toEqual(14);
date.setUTCMonth(1, 5);
expect(date.getUTCMonth()).toEqual(1);
expect(date.getUTCDate()).toEqual(5);
date.setUTCMonth(0, 0);
expect(date.getUTCMonth()).toEqual(11);
expect(date.getUTCDate()).toEqual(31);
});
it("accepts an optional parameter for date in setMonths", function() {
var date = new timezoneJS.Date(2000, 7, 14, 0, 0, 0, "America/New_York");
expect(date.getMonth()).toEqual(7);
expect(date.getDate()).toEqual(14);
date.setMonth(1, 5);
expect(date.getMonth()).toEqual(1);
expect(date.getDate()).toEqual(5);
date.setMonth(0, 0);
expect(date.getMonth()).toEqual(11);
expect(date.getDate()).toEqual(31);
});
// Hours
it("accepts an optional parameter for minutes in setUTCHours", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCMinutes()).toEqual(0);
date.setUTCHours(0, 1);
expect(date.getUTCMinutes()).toEqual(1);
date.setUTCHours(0, 0);
expect(date.getUTCMinutes()).toEqual(0);
});
it("accepts an optional parameter for seconds in setUTCHours", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCSeconds()).toEqual(0);
date.setUTCHours(0, 1, 2);
expect(date.getUTCSeconds()).toEqual(2);
date.setUTCHours(0, 0, 0);
expect(date.getUTCSeconds()).toEqual(0);
});
it("accepts an optional parameter for milliseconds in setUTCHours", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCMilliseconds()).toEqual(0);
date.setUTCHours(0, 1, 2, 3);
expect(date.getUTCMilliseconds()).toEqual(3);
date.setUTCHours(0, 0, 0, 0);
expect(date.getUTCMilliseconds()).toEqual(0);
});
it("accepts an optional parameter for minutes in setHours", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getMinutes()).toEqual(0);
date.setHours(0, 1);
expect(date.getMinutes()).toEqual(1);
date.setHours(0, 0);
expect(date.getMinutes()).toEqual(0);
});
it("accepts an optional parameter for seconds in setHours", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getSeconds()).toEqual(0);
date.setHours(0, 1, 2);
expect(date.getSeconds()).toEqual(2);
date.setHours(0, 0, 0);
expect(date.getSeconds()).toEqual(0);
});
it("accepts an optional parameter for milliseconds in setHours", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getMilliseconds()).toEqual(0);
date.setHours(0, 1, 2, 3);
expect(date.getMilliseconds()).toEqual(3);
date.setHours(0, 0, 0, 0);
expect(date.getMilliseconds()).toEqual(0);
});
// Minutes
it("accepts an optional parameter for seconds in setUTCMinutes", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCSeconds()).toEqual(0);
date.setUTCMinutes(0, 1);
expect(date.getUTCSeconds()).toEqual(1);
date.setUTCMinutes(0, 0);
expect(date.getUTCSeconds()).toEqual(0);
});
it("accepts an optional parameter for milliseconds in setUTCMinutes", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCMilliseconds()).toEqual(0);
date.setUTCMinutes(0, 1, 2);
expect(date.getUTCMilliseconds()).toEqual(2);
date.setUTCMinutes(0, 0, 0);
expect(date.getUTCMilliseconds()).toEqual(0);
});
it("accepts an optional parameter for seconds in setMinutes", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getSeconds()).toEqual(0);
date.setMinutes(0, 1);
expect(date.getSeconds()).toEqual(1);
date.setMinutes(0, 0);
expect(date.getSeconds()).toEqual(0);
});
it("accepts an optional parameter for milliseconds in setMinutes", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getMilliseconds()).toEqual(0);
date.setMinutes(0, 1, 2);
expect(date.getMilliseconds()).toEqual(2);
date.setMinutes(0, 0, 0);
expect(date.getMilliseconds()).toEqual(0);
});
// Seconds
it("accepts an optional parameter for milliseconds in setUTCSeconds", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "Etc/UTC");
expect(date.getUTCMilliseconds()).toEqual(0);
date.setUTCSeconds(0, 1);
expect(date.getUTCMilliseconds()).toEqual(1);
date.setUTCSeconds(0, 0);
expect(date.getUTCMilliseconds()).toEqual(0);
});
it("accepts an optional parameter for milliseconds in setSeconds", function() {
var date = new timezoneJS.Date(2000, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getMilliseconds()).toEqual(0);
date.setSeconds(0, 1);
expect(date.getMilliseconds()).toEqual(1);
date.setSeconds(0, 0);
expect(date.getMilliseconds()).toEqual(0);
});
it("handles static dst offsets in Zones like '1:00' instead of DST rule references.", function(){
var date = new timezoneJS.Date(Date.UTC(2012, 2, 1, 0, 0, 0, 0), "Pacific/Apia");
expect(date.getTimezoneOffset()).toBe(-840);
expect(date.toString("yyyy-MM-dd HH:mm:ss Z")).toBe("2012-03-01 14:00:00 WSDT");
});
it("returns the milis value for setTime", function() {
var date = new timezoneJS.Date("America/New_York");
expect(date.setTime(123456789)).toEqual(123456789);
});
it("returns the milis value for every set* command", function() {
milis = 1193851822000
var date = new timezoneJS.Date(milis, "America/New_York");
expect(date.setFullYear(date.getFullYear())).toEqual(milis);
expect(date.setMonth(date.getMonth())).toEqual(milis);
expect(date.setDate(date.getDate())).toEqual(milis);
expect(date.setHours(date.getHours())).toEqual(milis);
expect(date.setMinutes(date.getMinutes())).toEqual(milis);
expect(date.setSeconds(date.getSeconds())).toEqual(milis);
expect(date.setMilliseconds(date.getMilliseconds())).toEqual(milis);
});
it("returns the milis value for every setUTC* command", function() {
milis = 1193851822000
var date = new timezoneJS.Date(milis, "America/New_York");
expect(date.setUTCFullYear(date.getUTCFullYear())).toEqual(milis);
expect(date.setUTCMonth(date.getUTCMonth())).toEqual(milis);
expect(date.setUTCDate(date.getUTCDate())).toEqual(milis);
expect(date.setUTCHours(date.getUTCHours())).toEqual(milis);
expect(date.setUTCMinutes(date.getUTCMinutes())).toEqual(milis);
expect(date.setUTCSeconds(date.getUTCSeconds())).toEqual(milis);
expect(date.setUTCMilliseconds(date.getUTCMilliseconds())).toEqual(milis);
});
it("handles getYear appropriately strangely (to spec)", function() {
// http://www.ecma-international.org/ecma-262/5.1/#sec-B.2.4
var date = new timezoneJS.Date(1998, 11, 31, 0, 0, 0, "America/New_York");
expect(date.getYear()).toEqual(98);
date.setFullYear(2013);
expect(date.getYear()).toEqual(113);
});
it("handles setYear appropriately strangely (to spec)", function() {
// http://www.ecma-international.org/ecma-262/5.1/#sec-B.2.5
var date = new timezoneJS.Date(2001, 11, 31, 0, 0, 0, "America/New_York");
date.setYear(98)
expect(date.getFullYear()).toEqual(1998);
date.setYear(2003);
expect(date.getFullYear()).toEqual(2003);
});
});

View File

@@ -0,0 +1,86 @@
var fs = require('fs');
(function () {
var root = this;
var TestUtils = {};
if (typeof exports !== 'undefined') {
TestUtils = exports;
} else {
TestUtils = root.TestUtils = {};
}
var init = function (timezoneJS, options) {
var opts = {
async: false,
loadingScheme: timezoneJS.timezone.loadingSchemes.LAZY_LOAD
};
for (var k in (options || {})) {
opts[k] = options[k];
}
timezoneJS.timezone.transport = function (opts) {
// No success handler, what's the point?
if (opts.async) {
if (typeof opts.success !== 'function') return;
opts.error = opts.error || console.error;
return fs.readFile(opts.url, 'utf8', function (err, data) {
return err ? opts.error(err) : opts.success(data);
});
}
return fs.readFileSync(opts.url, 'utf8');
};
timezoneJS.timezone.loadingScheme = opts.loadingScheme;
timezoneJS.timezone.defaultZoneFile = opts.defaultZoneFile;
if (opts.loadingScheme !== timezoneJS.timezone.loadingSchemes.MANUAL_LOAD) {
//Set up again
timezoneJS.timezone.zoneFileBasePath = 'lib/tz';
timezoneJS.timezone.init(opts);
}
return timezoneJS;
};
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);
};
TestUtils.parseISO = function (timestring) {
var pat = '^(?:([+-]?[0-9]{4,})(?:-([0-9]{2})(?:-([0-9]{2}))?)?)?' +
'(?:T(?:([0-9]{2})(?::([0-9]{2})(?::([0-9]{2})(?:\\.' +
'([0-9]{3}))?)?)?)?(Z|[-+][0-9]{2}:[0-9]{2})?)?$';
var match = timestring.match(pat);
if (match) {
var parts = {
year: match[1] || 0,
month: match[2] || 1,
day: match[3] || 1,
hour: match[4] || 0,
minute: match[5] || 0,
second: match[6] || 0,
milli: match[7] || 0,
offset: match[8] || "Z"
};
var utcDate = Date.UTC(parts.year, parts.month-1, parts.day,
parts.hour, parts.minute, parts.second, parts.milli);
if (parts.offset !== "Z") {
match = parts.offset.match('([-+][0-9]{2})(?::([0-9]{2}))?');
if (!match) {
return NaN;
}
var offset = match[1]*60*60*1000+(match[2] || 0)*60*1000;
utcDate -= offset;
}
return new Date(utcDate);
}
return null;
};
}).call(this);

View File

@@ -0,0 +1,37 @@
var TestUtils = require('./test-utils')
, parseISO = TestUtils.parseISO
, date = require('../src/date');
describe('TimezoneJS', function () {
it('should async preload everything correctly', function () {
var i = 0
, timezoneJS
, sampleTz;
runs(function () {
timezoneJS = TestUtils.getTimezoneJS({
loadingScheme: date.timezone.loadingSchemes.PRELOAD_ALL,
async: true,
callback: function () {
//Make sure more than 1 zone is loaded
for (var k in timezoneJS.timezone.loadedZones) {
i++;
}
sampleTz = timezoneJS.timezone.getTzInfo(new Date(), 'Asia/Bangkok');
}
});
});
waitsFor(function () {
return i > 0;
}, 'zones should be loaded', 100);
runs(function () {
expect(timezoneJS.timezone.loadingScheme).toEqual(date.timezone.loadingSchemes.PRELOAD_ALL);
expect(i).toEqual(timezoneJS.timezone.zoneFiles.length);
expect(sampleTz).toBeDefined();
expect(sampleTz.tzAbbr).toEqual('ICT');
});
});
});

View File

@@ -0,0 +1,15 @@
var TestUtils = require('./test-utils')
, parseISO = TestUtils.parseISO
, date = require('../src/date')
, timezoneJS = TestUtils.getTimezoneJS({
defaultZoneFile: 'asia'
});
describe('TimezoneJS', function () {
it('should preload everything correctly', function () {
expect(timezoneJS.timezone.loadingScheme).toEqual(date.timezone.loadingSchemes.LAZY_LOAD);
expect(timezoneJS.timezone.loadedZones.asia).toBe(true);
sampleTz = timezoneJS.timezone.getTzInfo(new Date(), 'Asia/Bangkok');
expect(sampleTz).toBeDefined();
expect(sampleTz.tzAbbr).toEqual('ICT');
});
});

View File

@@ -0,0 +1,25 @@
var TestUtils = require('./test-utils')
, parseISO = TestUtils.parseISO
, date = require('../src/date')
, timezoneJS = TestUtils.getTimezoneJS({
loadingScheme: date.timezone.loadingSchemes.MANUAL_LOAD
});
describe('TimezoneJS', function () {
it('should manually load everything correctly', function () {
var i = 0
, sampleTz;
expect(timezoneJS.timezone.loadingScheme).toEqual(date.timezone.loadingSchemes.MANUAL_LOAD);
//Let's load some stuff
timezoneJS.timezone.loadZoneJSONData('lib/all_cities.json', true);
expect(Object.keys(timezoneJS.timezone.zones).length > 100).toBeTruthy();
sampleTz = timezoneJS.timezone.getTzInfo(new Date(), 'Asia/Bangkok');
expect(sampleTz).toBeDefined();
expect(sampleTz.tzAbbr).toEqual('ICT');
dt = new timezoneJS.Date();
dt.setTimezone('America/Chicago');
expect(dt.getTimezoneAbbreviation()).toMatch(/C(S|D)T/);
dt.setTimezone('America/New_York');
expect(dt.getTimezoneAbbreviation()).toMatch(/E(S|D)T/);
});
});

View File

@@ -0,0 +1,23 @@
var TestUtils = require('./test-utils')
, parseISO = TestUtils.parseISO
, date = require('../src/date')
, timezoneJS = TestUtils.getTimezoneJS({
loadingScheme: date.timezone.loadingSchemes.PRELOAD_ALL
});
describe('TimezoneJS', function () {
it('should preload everything correctly', function () {
var i = 0
, sampleTz;
expect(timezoneJS.timezone.loadingScheme).toEqual(date.timezone.loadingSchemes.PRELOAD_ALL);
//Make sure more than 1 zone is loaded
for (var k in timezoneJS.timezone.loadedZones) {
i++;
}
expect(i).toEqual(timezoneJS.timezone.zoneFiles.length);
i = 0;
sampleTz = timezoneJS.timezone.getTzInfo(new Date(), 'Asia/Bangkok');
expect(sampleTz).toBeDefined();
expect(sampleTz.tzAbbr).toEqual('ICT');
expect(new timezoneJS.Date('America/New_York').getTimezoneOffset() > 0).toBe(true);
});
});

View File

@@ -0,0 +1,176 @@
var TestUtils = require('./test-utils')
, parseISO = TestUtils.parseISO
, timezoneJS = TestUtils.getTimezoneJS();
describe('TimezoneJS', function () {
it('should get America/Chicago DST time correctly', function () {
var testDstLeap = function (arr) {
var expectedArr = [360, 300, 300, 360];
var dt;
var actual;
var expected;
for (var i = 0; i < arr.length; i++) {
dt = timezoneJS.timezone.getTzInfo(parseISO(arr[i]), 'America/Chicago');
actual = dt.tzOffset;
expected = expectedArr[i];
expect(actual).toEqual(expected);
}
};
testDstLeap(['2004-04-04', '2004-04-05', '2004-10-31', '2004-11-01']);
testDstLeap(['2005-04-03', '2005-04-04', '2005-10-30', '2005-10-31']);
testDstLeap(['2006-04-02', '2006-04-03', '2006-10-29', '2006-10-30']);
// 2007 -- new DST rules start here
testDstLeap(['2007-03-11', '2007-03-12', '2007-11-04', '2007-11-05']);
testDstLeap(['2008-03-09', '2008-03-10', '2008-11-02', '2008-11-03']);
testDstLeap(['2009-03-08', '2009-03-09', '2009-11-01', '2009-11-02']);
testDstLeap(['2010-03-14', '2010-03-15', '2010-11-07', '2010-11-08']);
testDstLeap(['2011-03-13', '2011-03-14', '2011-11-06', '2011-11-07']);
});
it('should get tzOffset of America/Sao_Paulo correctly', function () {
// Source: http://www.timeanddate.com/worldclock/clockchange.html?n=233
// Standard: GMT-3 from Feb 16 - Nov 1
// Daylight: GMT-2 from Nov 2 - Feb 16
var dt;
// 2008
//dt = timezoneJS.timezone.getTzInfo(parseISO('2008-02-16-02:00'), 'America/Sao_Paulo');
//expect(120, dt.tzOffset);
dt = timezoneJS.timezone.getTzInfo(parseISO('2008-02-17'), 'America/Sao_Paulo');
expect(dt.tzOffset).toEqual(180);
dt = timezoneJS.timezone.getTzInfo(parseISO('2008-10-11'), 'America/Sao_Paulo');
expect(dt.tzOffset).toEqual(180);
dt = timezoneJS.timezone.getTzInfo(parseISO('2008-10-19'), 'America/Sao_Paulo');
expect(dt.tzOffset).toEqual(120);
});
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 () {
// Source: http://www.timeanddate.com/worldclock/city.html?n=110
// Changes every year!
var dt;
// 2008
dt = timezoneJS.timezone.getTzInfo(parseISO('2008-03-28T01:59:59'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-120);
dt = timezoneJS.timezone.getTzInfo(parseISO('2008-03-28T03:00:01'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-180);
dt = timezoneJS.timezone.getTzInfo(parseISO('2008-10-05T00:59:59'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-180);
dt = timezoneJS.timezone.getTzInfo(parseISO('2008-10-05T03:00:01'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-120);
// 2009
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-03-27T01:59:59'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-120);
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-03-27T03:00:01'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-180);
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-09-27T00:59:59'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-180);
dt = timezoneJS.timezone.getTzInfo(parseISO('2009-09-27T03:00:01'), 'Asia/Jerusalem');
expect(dt.tzOffset).toEqual(-120);
});
it('should get abbreviation of central EU time correctly', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-01-01'), 'Europe/Berlin'); // winter time (CET) for sure
expect(dt.tzAbbr).toEqual('CET');
});
it('should get abbr for central EU summer time correctly', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-07-01'), 'Europe/Berlin'); // summer time (CEST) for sure
expect(dt.tzAbbr, 'CEST');
});
it('should get abbr for British Standard time correctly', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-01-01'), 'Europe/London'); // winter time (GMT) for sure
expect(dt.tzAbbr, 'GMT');
});
it('should get abbr for British summer time correctly', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-07-01'), 'Europe/London'); // summer time (BST) for sure
expect(dt.tzAbbr, 'BST');
});
it('should get abbr CET from tz info of 2010-03-28T01:59:59', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-28T01:59:59'), 'Europe/Berlin'); // CET, from local time
expect(dt.tzAbbr).toEqual('CET');
});
it('should get abbr CEST from tz info of 2010-03-08T03:00:00', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-28T03:00:00'), 'Europe/Berlin'); // CEST, from local time
expect(dt.tzAbbr, 'CEST');
});
it('should get abbr CET from tz info of 2010-03-08T00:59:59 UTC', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-28T00:59:59'), 'Europe/Berlin', true); // CEST, from local time
expect(dt.tzAbbr, 'CET');
});
it('should get abbr CEST from tz info of 2010-03-08T01:00:00 UTC', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-28T01:00:00'), 'Europe/Berlin', true); // CEST, from local time
expect(dt.tzAbbr, 'CEST');
});
it('should get abbr CST from 2010-03-14T01:59:59 Chicago', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-14T01:59:59'), 'America/Chicago'); // CST, from local time
expect(dt.tzAbbr).toEqual('CST');
});
it('should get abbr CDT from 2010-03-14T03:00:00 Chicago', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-14T03:00:00'), 'America/Chicago'); // CST, from local time
expect(dt.tzAbbr).toEqual('CDT');
});
it('should get abbr CST from 2010-03-14T07:59:59 UTC', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-14T07:59:59'), 'America/Chicago', true); // CST, from local time
expect(dt.tzAbbr).toEqual('CST');
});
it('should get abbr CDT from 2010-03-14T08:00:00 Chicago', function () {
var dt = timezoneJS.timezone.getTzInfo(parseISO('2010-03-14T08:00:00'), 'America/Chicago', true); // CST, from local time
expect(dt.tzAbbr).toEqual('CDT');
});
//This is for issue #1 in github
it('should not get null in getAllZones', function () {
var zones = timezoneJS.timezone.getAllZones();
for (var i = 0; i < zones; i++) {
expect(zones[i]).not.toBe(null);
}
});
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.'));
});
});

993
js/timezone-js/src/date.js Normal file
View File

@@ -0,0 +1,993 @@
// -----
// 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.
//
// The constructor function and setter methods use proxy JavaScript Date objects behind the scenes, so you can use strings like '10/22/2006' with the constructor. You also get the same sensible wraparound behavior with numeric parameters (like setting a value of 14 for the month wraps around to the next March).
//
// The other significant difference from the built-in JavaScript Date is that `timezoneJS.Date` also has named properties that store the values of year, month, date, etc., so it can be directly serialized to JSON and used for data transfer.
/*
* 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
*/
(function () {
// Standard initialization stuff to make sure the library is
// usable on both client and server (node) side.
"use strict";
var root = this;
var timezoneJS;
if (typeof exports !== 'undefined') {
timezoneJS = exports;
} else {
timezoneJS = root.timezoneJS = {};
}
timezoneJS.VERSION = '0.4.4';
// Grab the ajax library from global context.
// This can be jQuery, Zepto or fleegix.
// You can also specify your own transport mechanism by declaring
// `timezoneJS.timezone.transport` to a `function`. More details will follow
var $ = root.$ || root.jQuery || root.Zepto
, fleegix = root.fleegix
, _arrIndexOf
// 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']
, 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
//From https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
//Extending Array prototype causes IE to iterate thru extra element
_arrIndexOf = Array.prototype.indexOf || function (el) {
if (this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n !== Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === el) {
return k;
}
}
return -1;
};
// Format a number to the length = digits. For ex:
//
// `_fixWidth(2, 2) = '02'`
//
// `_fixWidth(1998, 2) = '98'`
//
// This is used to pad numbers in converting date to string in ISO standard.
var _fixWidth = function (number, digits) {
if (typeof number !== "number") { throw "not a number: " + number; }
var s = number.toString();
if (number.length > digits) {
return number.substr(number.length - digits, number.length);
}
while (s.length < digits) {
s = '0' + s;
}
return s;
};
// Abstraction layer for different transport layers, including fleegix/jQuery/Zepto
//
// Object `opts` include
//
// - `url`: url to ajax query
//
// - `async`: true for asynchronous, false otherwise. If false, return value will be response from URL. This is true by default
//
// - `success`: success callback function
//
// - `error`: error callback function
// Returns response from URL if async is false, otherwise the AJAX request object itself
var _transport = function (opts) {
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.');
}
if (!opts) return;
if (!opts.url) throw new Error ('URL must be specified');
if (!('async' in opts)) opts.async = true;
if (!opts.async) {
return fleegix && fleegix.xhr
? fleegix.xhr.doReq({ url: opts.url, async: false })
: $.ajax({ url : opts.url, async : false }).responseText;
}
return fleegix && fleegix.xhr
? fleegix.xhr.send({
url : opts.url,
method : 'get',
handleSuccess : opts.success,
handleErr : opts.error
})
: $.ajax({
url : opts.url,
dataType: 'text',
method : 'GET',
error : opts.error,
success : opts.success
});
};
// Constructor, which is similar to that of the native Date object itself
timezoneJS.Date = function () {
var args = Array.prototype.slice.apply(arguments)
, dt = null
, tz = null
, arr = [];
//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];
}
if (typeof args[args.length - 1] === 'string' && TZ_REGEXP.test(args[args.length - 1])) {
tz = args.pop();
}
switch (args.length) {
case 0:
dt = new Date();
break;
case 1:
dt = new Date(args[0]);
break;
default:
for (var i = 0; i < 7; i++) {
arr[i] = args[i] || 0;
}
dt = new Date(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6]);
break;
}
this._useCache = false;
this._tzInfo = {};
this._day = 0;
this.year = 0;
this.month = 0;
this.date = 0;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.milliseconds = 0;
this.timezone = tz || null;
//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.
if (arr.length) {
this.setFromDateObjProxy(dt);
} else {
this.setFromTimeProxy(dt.getTime(), tz);
}
};
// Implements most of the native Date object
timezoneJS.Date.prototype = {
getDate: function () { return this.date; },
getDay: function () { return this._day; },
getFullYear: function () { return this.year; },
getMonth: function () { return this.month; },
getYear: function () { return this.year - 1900; },
getHours: function () { return this.hours; },
getMilliseconds: function () { return this.milliseconds; },
getMinutes: function () { return this.minutes; },
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 () {
return this._timeProxy + (this.getTimezoneOffset() * 60 * 1000);
},
getTimezone: function () { return this.timezone; },
getTimezoneOffset: function () { return this.getTimezoneInfo().tzOffset; },
getTimezoneAbbreviation: function () { return this.getTimezoneInfo().tzAbbr; },
getTimezoneInfo: function () {
if (this._useCache) return this._tzInfo;
var res;
// If timezone is specified, get the correct timezone info based on the Date given
if (this.timezone) {
res = this.timezone === 'Etc/UTC' || this.timezone === 'Etc/GMT'
? { tzOffset: 0, tzAbbr: 'UTC' }
: timezoneJS.timezone.getTzInfo(this._timeProxy, this.timezone);
}
// If no timezone was specified, use the local browser offset
else {
res = { tzOffset: this.getLocalOffset(), tzAbbr: null };
}
this._tzInfo = res;
this._useCache = true;
return res;
},
getUTCDateProxy: function () {
var dt = new Date(this._timeProxy);
dt.setUTCMinutes(dt.getUTCMinutes() + this.getTimezoneOffset());
return dt;
},
setDate: function (date) {
this.setAttribute('date', date);
return this.getTime();
},
setFullYear: function (year, month, date) {
if (date !== undefined) { this.setAttribute('date', 1); }
this.setAttribute('year', year);
if (month !== undefined) { this.setAttribute('month', month); }
if (date !== undefined) { this.setAttribute('date', date); }
return this.getTime();
},
setMonth: function (month, date) {
this.setAttribute('month', month);
if (date !== undefined) { this.setAttribute('date', date); }
return this.getTime();
},
setYear: function (year) {
year = Number(year);
if (0 <= year && year <= 99) { year += 1900; }
this.setUTCAttribute('year', year);
return this.getTime();
},
setHours: function (hours, minutes, seconds, milliseconds) {
this.setAttribute('hours', hours);
if (minutes !== undefined) { this.setAttribute('minutes', minutes); }
if (seconds !== undefined) { this.setAttribute('seconds', seconds); }
if (milliseconds !== undefined) { this.setAttribute('milliseconds', milliseconds); }
return this.getTime();
},
setMinutes: function (minutes, seconds, milliseconds) {
this.setAttribute('minutes', minutes);
if (seconds !== undefined) { this.setAttribute('seconds', seconds); }
if (milliseconds !== undefined) { this.setAttribute('milliseconds', milliseconds); }
return this.getTime();
},
setSeconds: function (seconds, milliseconds) {
this.setAttribute('seconds', seconds);
if (milliseconds !== undefined) { this.setAttribute('milliseconds', milliseconds); }
return this.getTime();
},
setMilliseconds: function (milliseconds) {
this.setAttribute('milliseconds', milliseconds);
return this.getTime();
},
setTime: function (n) {
if (isNaN(n)) { throw new Error('Units must be a number.'); }
this.setFromTimeProxy(n, this.timezone);
return this.getTime();
},
setUTCFullYear: function (year, month, date) {
if (date !== undefined) { this.setUTCAttribute('date', 1); }
this.setUTCAttribute('year', year);
if (month !== undefined) { this.setUTCAttribute('month', month); }
if (date !== undefined) { this.setUTCAttribute('date', date); }
return this.getTime();
},
setUTCMonth: function (month, date) {
this.setUTCAttribute('month', month);
if (date !== undefined) { this.setUTCAttribute('date', date); }
return this.getTime();
},
setUTCDate: function (date) {
this.setUTCAttribute('date', date);
return this.getTime();
},
setUTCHours: function (hours, minutes, seconds, milliseconds) {
this.setUTCAttribute('hours', hours);
if (minutes !== undefined) { this.setUTCAttribute('minutes', minutes); }
if (seconds !== undefined) { this.setUTCAttribute('seconds', seconds); }
if (milliseconds !== undefined) { this.setUTCAttribute('milliseconds', milliseconds); }
return this.getTime();
},
setUTCMinutes: function (minutes, seconds, milliseconds) {
this.setUTCAttribute('minutes', minutes);
if (seconds !== undefined) { this.setUTCAttribute('seconds', seconds); }
if (milliseconds !== undefined) { this.setUTCAttribute('milliseconds', milliseconds); }
return this.getTime();
},
setUTCSeconds: function (seconds, milliseconds) {
this.setUTCAttribute('seconds', seconds);
if (milliseconds !== undefined) { this.setUTCAttribute('milliseconds', milliseconds); }
return this.getTime();
},
setUTCMilliseconds: function (milliseconds) {
this.setUTCAttribute('milliseconds', milliseconds);
return this.getTime();
},
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'); },
toLocaleString: function () {},
toLocaleDateString: function () {},
toLocaleTimeString: function () {},
toSource: function () {},
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:
toString: function (format, tz) {
// Default format is the same as toISOString
if (!format) format = 'yyyy-MM-dd HH:mm:ss';
var result = format;
var tzInfo = tz ? timezoneJS.timezone.getTzInfo(this.getTime(), tz) : this.getTimezoneInfo();
var _this = this;
// If timezone is specified, get a clone of the current Date object and modify it
if (tz) {
_this = this.clone();
_this.setTimezone(tz);
}
var hours = _this.getHours();
return result
// fix the same characters in Month names
.replace(/a+/g, function () { return 'k'; })
// `y`: year
.replace(/y+/g, function (token) { return _fixWidth(_this.getFullYear(), token.length); })
// `d`: date
.replace(/d+/g, function (token) { return _fixWidth(_this.getDate(), token.length); })
// `m`: minute
.replace(/m+/g, function (token) { return _fixWidth(_this.getMinutes(), token.length); })
// `s`: second
.replace(/s+/g, function (token) { return _fixWidth(_this.getSeconds(), token.length); })
// `S`: millisecond
.replace(/S+/g, function (token) { return _fixWidth(_this.getMilliseconds(), token.length); })
// `M`: month. Note: `MM` will be the numeric representation (e.g February is 02) but `MMM` will be text representation (e.g February is Feb)
.replace(/M+/g, function (token) {
var _month = _this.getMonth(),
_len = token.length;
if (_len > 3) {
return timezoneJS.Months[_month];
} else if (_len > 2) {
return timezoneJS.Months[_month].substring(0, _len);
}
return _fixWidth(_month + 1, _len);
})
// `k`: AM/PM
.replace(/k+/g, function () {
if (hours >= 12) {
if (hours > 12) {
hours -= 12;
}
return 'PM';
}
return 'AM';
})
// `H`: hour
.replace(/H+/g, function (token) { return _fixWidth(hours, token.length); })
// `E`: day
.replace(/E+/g, function (token) { return DAYS[_this.getDay()].substring(0, token.length); })
// `Z`: timezone abbreviation
.replace(/Z+/gi, function () { return tzInfo.tzAbbr; });
},
toUTCString: function () { return this.toGMTString(); },
civilToJulianDayNumber: function (y, m, d) {
var a;
// Adjust for zero-based JS-style array
m++;
if (m > 12) {
a = parseInt(m/12, 10);
m = m % 12;
y += a;
}
if (m <= 2) {
y -= 1;
m += 12;
}
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;
return jDt;
},
getLocalOffset: function () {
return this._dateProxy.getTimezoneOffset();
}
};
timezoneJS.timezone = new function () {
var _this = this
, 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.'); }
function builtInLoadZoneFile(fileName, opts) {
var url = _this.zoneFileBasePath + '/' + fileName;
return !opts || !opts.async
? _this.parseZones(_this.transport({ url : url, async : false }))
: _this.transport({
async: true,
url : url,
success : function (str) {
if (_this.parseZones(str) && typeof opts.callback === 'function') {
opts.callback();
}
return true;
},
error : function () {
throw new Error('Error retrieving "' + url + '" zoneinfo files');
}
});
}
function getRegionForTimezone(tz) {
var exc = regionExceptions[tz]
, reg
, ret;
if (exc) return exc;
reg = tz.split('/')[0];
ret = regionMap[reg];
// If there's nothing listed in the main regions for this TZ, check the 'backward' links
if (ret) return ret;
var link = _this.zones[tz];
if (typeof link === 'string') {
return getRegionForTimezone(link);
}
// Backward-compat file hasn't loaded yet, try looking in there
if (!_this.loadedZones.backward) {
// 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');
return getRegionForTimezone(tz);
}
invalidTZError(tz);
}
function parseTimeString(str) {
var pat = /(\d+)(?::0*(\d*))?(?::0*(\d*))?([wsugz])?$/;
var hms = str.match(pat);
hms[1] = parseInt(hms[1], 10);
hms[2] = hms[2] ? parseInt(hms[2], 10) : 0;
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 actual zone
while (typeof zoneList === "string") {
t = zoneList;
zoneList = _this.zones[t];
}
if (!zoneList) {
// Backward-compat file hasn't loaded yet, try looking in there
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');
return getZone(dt, tz);
}
invalidTZError(t);
}
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] && utcMillis > z[3]) break;
}
return zoneList[i+1];
}
function getBasicOffset(time) {
var off = parseTimeString(time)
, adj = time.charAt(0) === '-' ? -1 : 1;
off = adj * (((off[1] * 60 + off[2]) * 60 + off[3]) * 1000);
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)
function getRule(dt, zone, isUTC) {
var date = typeof dt === 'number' ? new Date(dt) : dt;
var ruleset = zone[1];
var basicOffset = zone[0];
// If the zone has a DST rule like '1:00', create a rule and return it
// instead of looking it up in the parsed rules
var staticDstMatch = ruleset.match(/^([0-9]):([0-9][0-9])$/);
if (staticDstMatch) {
return [-1000000,'max','-','Jan',1,parseTimeString('0:00'),parseInt(staticDstMatch[1]) * 60 + parseInt(staticDstMatch[2]), '-'];
}
//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) {
var offset = 0;
if (type === 'u' || type === 'g' || type === 'z') { // UTC
offset = 0;
} else if (type === 's') { // Standard Time
offset = basicOffset;
} else if (type === 'w' || !type) { // Wall Clock Time
offset = getAdjustedOffset(basicOffset, rule);
} else {
throw("unknown type " + type);
}
offset *= 60 * 1000; // to millis
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.
var convertRuleToExactDateAndTime = function (yearAndRule, prevRule) {
var year = yearAndRule[0]
, rule = yearAndRule[1];
// Assume that the rule applies to the year of the given date.
var hms = rule[5];
var effectiveDate;
if (!EXACT_DATE_TIME[year])
EXACT_DATE_TIME[year] = {};
// Result for given parameters is already stored
if (EXACT_DATE_TIME[year][rule])
effectiveDate = EXACT_DATE_TIME[year][rule];
else {
//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));
}
//Let's hunt for the date.
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, 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)));
}
}
EXACT_DATE_TIME[year][rule] = effectiveDate;
}
//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) {
effectiveDate = convertDateToUTC(effectiveDate, hms[4], prevRule);
}
return effectiveDate;
};
var findApplicableRules = function (year, ruleset) {
var applicableRules = [];
for (var i = 0; ruleset && i < ruleset.length; i++) {
//Exclude future rules.
if (ruleset[i][0] <= year &&
(
// Date is in a set range.
ruleset[i][1] >= year ||
// Date is in an "only" year.
(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.
applicableRules.push([year, ruleset[i]]);
}
}
return applicableRules;
};
var compareDates = function (a, b, prev) {
var year, rule;
if (a.constructor !== Date) {
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) {
a = convertDateToUTC(a, isUTC ? 'u' : 'w', prev);
}
if (b.constructor !== Date) {
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) {
b = convertDateToUTC(b, isUTC ? 'u' : 'w', prev);
}
a = Number(a);
b = Number(b);
return a - b;
};
var year = date.getUTCFullYear();
var applicableRules;
applicableRules = findApplicableRules(year, _this.rules[ruleset]);
applicableRules.push(date);
//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
// larger than the DST offset, which is probably always true.
// As the given date may indeed be close to a DST change, it may get sorted
// to a wrong position (off by one), which is corrected below.
applicableRules.sort(compareDates);
//If there are not enough past DST rules...
if (_arrIndexOf.call(applicableRules, date) < 2) {
applicableRules = applicableRules.concat(findApplicableRules(year-1, _this.rules[ruleset]));
applicableRules.sort(compareDates);
}
var pinpoint = _arrIndexOf.call(applicableRules, date);
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.
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.
return applicableRules[pinpoint + 1][1];
} else if (pinpoint === 0) {
//No applicable rule found in this and in previous year.
return null;
}
return applicableRules[pinpoint - 1][1];
}
function getAdjustedOffset(off, rule) {
return -Math.ceil(rule[6] - off);
}
function getAbbreviation(zone, rule) {
var res;
var base = zone[2];
if (base.indexOf('%s') > -1) {
var repl;
if (rule) {
repl = rule[7] === '-' ? '' : rule[7];
}
//FIXME: Right now just falling back to Standard --
// apparently ought to use the last valid rule,
// although in practice that always ought to be Standard
else {
repl = 'S';
}
res = base.replace('%s', repl);
}
else if (base.indexOf('/') > -1) {
//Chose one of two alternative strings.
res = base.split("/", 2)[rule[6] ? 1 : 0];
} else {
res = base;
}
return res;
}
this.zoneFileBasePath = null;
this.zoneFiles = ['africa', 'antarctica', 'asia', 'australasia', 'backward', 'etcetera', 'europe', 'northamerica', 'pacificnew', 'southamerica'];
this.loadingSchemes = {
PRELOAD_ALL: 'preloadAll',
LAZY_LOAD: 'lazyLoad',
MANUAL_LOAD: 'manualLoad'
};
this.loadingScheme = this.loadingSchemes.LAZY_LOAD;
this.loadedZones = {};
this.zones = {};
this.rules = {};
this.init = function (o) {
var opts = { async: true }
, def = this.loadingScheme === this.loadingSchemes.PRELOAD_ALL
? this.zoneFiles
: (this.defaultZoneFile || 'northamerica')
, done = 0
, callbackFn;
//Override default with any passed-in opts
for (var p in o) {
opts[p] = o[p];
}
if (typeof def === 'string') {
return this.loadZoneFile(def, opts);
}
//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++) {
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.
this.loadZoneFile = function (fileName, opts) {
if (typeof this.zoneFileBasePath === 'undefined') {
throw new Error('Please define a base path to your zone file directory -- timezoneJS.timezone.zoneFileBasePath.');
}
//Ignore already loaded zones.
if (this.loadedZones[fileName]) {
return;
}
this.loadedZones[fileName] = true;
return builtInLoadZoneFile(fileName, opts);
};
this.loadZoneJSONData = function (url, sync) {
var processData = function (data) {
data = eval('('+ data +')');
for (var z in data.zones) {
_this.zones[z] = data.zones[z];
}
for (var r in data.rules) {
_this.rules[r] = data.rules[r];
}
};
return sync
? processData(_this.transport({ url : url, async : false }))
: _this.transport({ url : url, success : processData });
};
this.loadZoneDataFromObject = function (data) {
if (!data) { return; }
for (var z in data.zones) {
_this.zones[z] = data.zones[z];
}
for (var r in data.rules) {
_this.rules[r] = data.rules[r];
}
};
this.getAllZones = function () {
var arr = [];
for (var z in this.zones) { arr.push(z); }
return arr.sort();
};
this.parseZones = function (str) {
var lines = str.split('\n')
, arr = []
, chunk = ''
, l
, zone = null
, rule = null;
for (var i = 0; i < lines.length; i++) {
l = lines[i];
if (l.match(/^\s/)) {
l = "Zone " + zone + l;
}
l = l.split("#")[0];
if (l.length > 3) {
arr = l.split(/\s+/);
chunk = arr.shift();
//Ignore Leap.
switch (chunk) {
case 'Zone':
zone = arr.shift();
if (!_this.zones[zone]) {
_this.zones[zone] = [];
}
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);
break;
case 'Rule':
rule = arr.shift();
if (!_this.rules[rule]) {
_this.rules[rule] = [];
}
//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);
break;
case 'Link':
//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.
_this.zones[arr[1]] = arr[0];
break;
}
}
}
return true;
};
//Expose transport mechanism and allow overwrite.
this.transport = _transport;
this.getTzInfo = function (dt, tz, isUTC) {
//Lazy-load any zones not yet loaded.
if (this.loadingScheme === this.loadingSchemes.LAZY_LOAD) {
//Get the correct region for the zone.
var zoneFile = getRegionForTimezone(tz);
if (!zoneFile) {
throw new Error('Not a valid timezone ID.');
}
if (!this.loadedZones[zoneFile]) {
//Get the file and parse it -- use synchronous XHR.
this.loadZoneFile(zoneFile);
}
}
var z = getZone(dt, tz);
var off = z[0];
//See if the offset needs adjustment.
var rule = getRule(dt, z, isUTC);
if (rule) {
off = getAdjustedOffset(off, rule);
}
var abbr = getAbbreviation(z, rule);
return { tzOffset: off, tzAbbr: abbr };
};
};
}).call(this);

View File

@@ -0,0 +1,56 @@
(function () {
var fs = require('fs')
, timezoneJS = require('./date')
, EXCLUDED = new RegExp('Makefile|factory|(\\.+)', 'i');
function parse(args) {
// Upgrade passed script args to real Array
if (args.length < 3) {
console.log('Usage: node node-preparse.js zoneFileDirectory [exemplarCities] > outputfile.json');
console.log('Ex. >>> node node-preparse.js olson_files "Asia/Tokyo, America/New_York, Europe/London" > major_cities.json');
console.log('Ex. >>> node node-preparse.js olson_files > all_cities.json');
return;
}
var baseDir = args[2]
, cities = args[3]
, result = {}
, _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.zoneFiles = fs.readdirSync(baseDir);
for (var i = 0; i < _tz.zoneFiles.length; i++) {
var zoneFile = _tz.zoneFiles[i];
if (EXCLUDED.test(zoneFile)) continue;
var zoneData = fs.readFileSync(baseDir + '/' + zoneFile, 'utf8');
_tz.parseZones(zoneData);
}
if (cities) {
cities = cities.replace(/ /g, '').split(',');
var zones = {};
var rules = {};
for (var i = 0; i < cities.length; i++) {
var city = cities[i];
zones[city] = _tz.zones[city];
}
for (var n in zones) {
var zList = zones[n];
for (var i = 0; i < zList.length; i++) {
var ruleKey = zList[i][1];
rules[ruleKey] = _tz.rules[ruleKey];
}
}
result.zones = zones;
result.rules = rules;
}
else {
result.zones = _tz.zones;
result.rules = _tz.rules;
}
console.log(JSON.stringify(result));
}
module.exports = parse(process.argv);
}).call(this);

View File

@@ -0,0 +1,65 @@
function readText(uri){
var jf = new java.io.File(uri);
var sb = new java.lang.StringBuffer();
var input = new java.io.BufferedReader(new java.io.FileReader(jf));
var line = "";
var str = "";
while((line = input.readLine()) != null){
sb.append(line);
sb.append(java.lang.System.getProperty("line.separator"));
}
// Cast to real JS String
str += sb.toString();
return str;
}
function main(args) {
// Upgrade passed script args to real Array
if (!args.length) {
print('Usage: rhino preparse.js zoneFileDirectory [exemplarCities] > outputfile.json');
print('Ex. >>> rhino preparse.js olson_files "Asia/Tokyo, America/New_York, Europe/London" > major_cities.json');
print('Ex. >>> rhino preparse.js olson_files > all_cities.json');
return;
}
var baseDir = args[0];
var cities = args[1];
load('date.js');
load('../../src/json.js');
var _tz = fleegix.date.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
for (var i = 0; i < _tz.zoneFiles.length; i++) {
var zoneFile = _tz.zoneFiles[i];
var zoneData = readText(baseDir + '/' + zoneFile);
_tz.parseZones(zoneData);
}
var result = {};
if (cities) {
cities = cities.replace(/ /g, '').split(',');
var zones = {};
var rules = {};
for (var i = 0; i < cities.length; i++) {
var city = cities[i];
zones[city] = _tz.zones[city];
}
for (var n in zones) {
var zList = zones[n];
for (var i = 0; i < zList.length; i++) {
var ruleKey = zList[i][1];
rules[ruleKey] = _tz.rules[ruleKey];
}
}
result.zones = zones;
result.rules = rules;
}
else {
result.zones = _tz.zones;
result.rules = _tz.rules
}
result = fleegix.json.serialize(result);
print(result);
}
main(arguments);

View File

@@ -0,0 +1,30 @@
#!/usr/bin/ruby
#
# Copyright 2009 Matthew Eernisse (mde@fleegix.org)
#
# 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.
#
# This is a sample script for stripping the copious comments
# from Olson timezone data files.
#
if ARGV.length == 0
print "Usage: strip_comments.rb /path/to/input/file\n"
exit
else
path = ARGV[0]
end
t = File.read(path)
t.gsub!(/^#.*\n/, '')
t.gsub!(/^\n/, '')
print t