{"id":13675391,"url":"https://github.com/mde/timezone-js","last_synced_at":"2025-10-03T01:31:14.773Z","repository":{"id":852971,"uuid":"583762","full_name":"mde/timezone-js","owner":"mde","description":"DEPRECATED: Timezone-enabled JavaScript Date object. Uses Olson zoneinfo files for timezone data.","archived":true,"fork":false,"pushed_at":"2017-06-24T19:52:01.000Z","size":243,"stargazers_count":827,"open_issues_count":4,"forks_count":193,"subscribers_count":35,"default_branch":"master","last_synced_at":"2024-04-29T21:15:21.711Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mde.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2010-03-28T19:30:15.000Z","updated_at":"2024-04-19T09:50:29.000Z","dependencies_parsed_at":"2022-08-16T11:10:37.638Z","dependency_job_id":null,"html_url":"https://github.com/mde/timezone-js","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mde%2Ftimezone-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mde%2Ftimezone-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mde%2Ftimezone-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mde%2Ftimezone-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mde","download_url":"https://codeload.github.com/mde/timezone-js/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235059234,"owners_count":18929279,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T12:00:39.737Z","updated_at":"2025-10-03T01:31:09.489Z","avatar_url":"https://github.com/mde.png","language":"JavaScript","readme":"# TimezoneJS.Date\n\n[![Build Status](https://secure.travis-ci.org/mde/timezone-js.png)](https://secure.travis-ci.org/mde/timezone-js)\n\nA 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.\n\n[Mailing list](http://groups.google.com/group/timezone-js)\n\n## Overview\n\nThe `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.\n\nThe 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).\n\nThe 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.\n\n## Setup\n\nThis section shows the most common way of setting up timezone-js. In the 'Customizing' section below you can find alternative approaches.\n\nFirst 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:\n\n\t\u003cscript type=\"text/javascript\" src=\"/js/timezone-js/src/date.js\"\u003e\n\nNext 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.)\n\nHere is an example of how to get the Olson time zone files:\n\n``` bash\n##!/bin/bash\n\n# NOTE: Run from your webroot\n\n# Create the /tz directory\nmkdir tz\n\n# Download the latest Olson files\ncurl ftp://ftp.iana.org/tz/tzdata-latest.tar.gz -o tz/tzdata-latest.tar.gz\n\n# Expand the files\ntar -xvzf tz/tzdata-latest.tar.gz -C tz\n\n# Optionally, you can remove the downloaded archives.\nrm tz/tzdata-latest.tar.gz\n```\n\nThen 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.\n\nPut 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:\n\n``` js\ntimezoneJS.timezone.zoneFileBasePath = '/tz';\ntimezoneJS.timezone.init({ callback: cb });\n```\n\nIf you use `timezoneJS.Date` with `Fleegix.js`, `jQuery` or `jQuery`-compatible libraries (like `Zepto.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.\n\n**NOTE**: By default `init()` is async so you'll need to specify a callback function such as `init({ callback: cb })`. Otherwise set `init({ async: false })` to turn off async.\n\n## Usage\n\nThe `timezoneJS.Date` constructor is compatible to the normal JavaScript Date constructor, but additional allows to pass an optional `tz` (timezone). In the following cases the passed date/time is unambiguous:\n\n``` js\ntimezoneJS.Date(millis, [tz])\ntimezoneJS.Date(Date, [tz])\ntimezoneJS.Date(dt_str_tz, [tz])\n```\n\n`dt_str_tz` is a date string containing timezone information, i.e. containing `Z`, `T` or a timezone offset matching the regular expression `/[+-][0-9]{4}/` (e.g. `+0200`). The [one-stop shop for cross-browser JavaScript Date parsing behavior](http://dygraphs.com/date-formats.html) provides detailed information about JavaScript date formats.\n\nIn the following cases the date is assumed to be a date in timezone `tz` or a locale date if `tz` is not provided:\n\n``` js\ntimezoneJS.Date(year, mon, day, [hour], [min], [second], [tz])\ntimezoneJS.Date(dt_str, [tz])\n```\n\n`dt_str` is a date string containing no timezone information.\n\n### Examples\n\nCreate a `timezoneJS.Date` the same way as a normal JavaScript Date, but append a timezone parameter on the end:\n\n``` js\nvar dt = new timezoneJS.Date('10/31/2008', 'America/New_York');\nvar dt = new timezoneJS.Date(2008, 9, 31, 11, 45, 'America/Los_Angeles');\n```\n\nNaturally enough, the `getTimezoneOffset` method returns the timezone offset in minutes based on the timezone you set for the date.\n\n``` js\n// Pre-DST-leap\nvar dt = new timezoneJS.Date(2006, 9, 29, 1, 59, 'America/Los_Angeles');\ndt.getTimezoneOffset(); =\u003e 420\n// Post-DST-leap\nvar dt = new timezoneJS.Date(2006, 9, 29, 2, 0, 'America/Los_Angeles');\ndt.getTimezoneOffset(); =\u003e 480\n```\n\nJust as you'd expect, the `getTime` method gives you the UTC timestamp for the given date:\n\n``` js\nvar dtA = new timezoneJS.Date(2007, 9, 31, 10, 30, 'America/Los_Angeles');\nvar dtB = new timezoneJS.Date(2007, 9, 31, 12, 30, 'America/Chicago');\n// Same timestamp\ndtA.getTime(); =\u003e 1193855400000\ndtB.getTime(); =\u003e 1193855400000\n```\n\nYou can set (or reset) the timezone using the `setTimezone` method:\n\n``` js\nvar dt = new timezoneJS.Date('10/31/2006', 'America/Juneau');\ndt.getTimezoneOffset(); =\u003e 540\ndt.setTimezone('America/Chicago');\ndt.getTimezoneOffset(); =\u003e 300\ndt.setTimezone('Pacific/Honolulu');\ndt.getTimezoneOffset(); =\u003e 600\n```\n\nThe `getTimezone` method tells you what timezone a `timezoneJS.Date` is set to:\n\n``` js\nvar dt = new timezoneJS.Date('12/27/2010', 'Asia/Tokyo');\ndt.getTimezone(); =\u003e 'Asia/Tokyo'\n```\n\nYou can use `getTimezoneAbbreviation` method to get timezone abbreviation:\n\n``` js\nvar dt = new timezoneJS.Date('10/31/2008', 'America/New_York');\ndt.getTimezoneAbbreviation(); =\u003e 'EDT'\n```\n\n## Customizing\n\nIf you don't change it, the timezone region that loads on\n initialization is North America (the Olson 'northamerica' file). To change that to another reqion, set `timezoneJS.timezone.defaultZoneFile` to your desired region, like so:\n ``` js\ntimezoneJS.timezone.zoneFileBasePath = '/tz';\ntimezoneJS.timezone.defaultZoneFile = 'asia';\ntimezoneJS.timezone.init();\n```\n\nIf you want to preload multiple regions, set it to an array, like this:\n\n``` js\ntimezoneJS.timezone.zoneFileBasePath = '/tz';\ntimezoneJS.timezone.defaultZoneFile = ['asia', 'backward', 'northamerica', 'southamerica'];\ntimezoneJS.timezone.init();\n```\n\nBy default the `timezoneJS.Date` timezone code lazy-loads the timezone data files, pulling them down and parsing them only as needed.\n\nFor 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.\n\nYou can change this behavior by changing the value of `timezoneJS.timezone.loadingScheme`. The three possible values are:\n\n1. `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.\n2. `timezoneJS.timezone.loadingSchemes.LAZY_LOAD` -- the default. Loads some amount of data up front, then lazy-loads any other needed timezone data as needed.\n3. `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.\n\n## Ready-made tzdata NPM modules\n\nIf you use NPM, and you want to load the time zone data synchronously, you can use one or more of the tzdata* NPM modules. That way, you do not have to download the IANA zone files manually, you can just run `npm update` to get the latest data.\n\nThe [tzdata](https://www.npmjs.com/package/tzdata) module contains all time zones. There are other modules, e.g. [tzdata-northamerica](https://www.npmjs.com/package/tzdata-northamerica) that contain subsets of the zones.\n\nFirst, install timezone-js and one or more of the tzdata modules.\n```bash\nnpm install timezone-js tzdata\n```\n\nThen, initialize timezone-js with the data:\n```javascript\nvar timezoneJS = require(\"timezone-js\");\nvar tzdata = require(\"tzdata\");\n\nvar _tz = timezoneJS.timezone;\n_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;\n_tz.loadZoneDataFromObject(tzdata);\n\nvar dt = new timezoneJS.Date(2006, 9, 29, 1, 59, 'America/Los_Angeles');\n```\n\n## Pre-Parsed JSON Data\n\nIf 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.\n\nThe src directory contains 2 command-line JavaScript scripts that can generate this kind of JSON data:\n\n- `node-preparse.js`: Uses Node to preparse and populate data.\n- `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.\n\nUse the script like this:\n\n``` bash\nrhino preparse.js zoneFileDirectory [exemplarCities] \u003e outputfile.json\n```\n\nOr:\n\n``` bash\nnode node-preparse.js zoneFileDirectory [exemplarCities] \u003e outputfile.json\n```\n\nThe 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.\n\n``` bash\nrhino preparse.js olson_files \\\n\"Asia/Tokyo, America/New_York, Europe/London\" \\\n\u003e major_cities.json\n\nrhino preparse.js olson_files \u003e all_cities.json\n```\n\nOr:\n\n``` bash\nnode node-preparse.js olson_files \\\n\"Asia/Tokyo, America/New_York, Europe/London\" \\\n\u003e major_cities.json\n\nnode node-preparse.js olson_files \u003e all_cities.json\n```\n\nOnce 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:\n\n``` js\nvar _tz = timezoneJS.timezone;\n_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;\n_tz.loadZoneJSONData('/major_cities.json', true);\n```\n\nSince 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.\n\n## Compressing\n\nThe Olson timezone data files are simple, space- and linefeed-delimited data. The abundance of whitespace means they compress very, very well.\n\nIf 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.)**\n\nJust 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.\n\nThe `src` directory has a sample Ruby script that you can use to strip comments from Olson data files.\n\n## Development\nThis project use [Jake](https://github.com/mde/jake) to build. In order to see available tasks, do `jake -T`. The build sequence is:\n\n- `jake test:init`: Download and extract tz files to `lib/tz`.\n- `jake test`: Run `jasmine-node`.\n\nFeel free to fork and modify at your own will.\nThe source code is annotated and doc can be generated with `jake doc`.\n\n## License\n\n\nCopyright 2010 Matthew Eernisse (mde@fleegix.org) and Open Source Applications Foundation.\n\nLicensed 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\n\nUnless 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.\n\nCredits: Ideas included from incomplete JS implementation of Olson parser, \"XMLDAte\" by Philippe Goetz (philippe.goetz@wanadoo.fr)\n\nContributions:\n\n- Jan Niehusmann\n- Ricky Romero\n- Preston Hunt (prestonhunt@gmail.com)\n- Dov. B Katz (dov.katz@morganstanley.com)\n- Peter Bergström (pbergstr@mac.com)\n- Long Ho (@longlho)\n- Eugeny Loy (eugeny.loy@gmail.com)\n","funding_links":[],"categories":["Date","Timezone all around","Date [🔝](#readme)","日期"],"sub_categories":["Runner","运行器","运行器e2e测试"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmde%2Ftimezone-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmde%2Ftimezone-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmde%2Ftimezone-js/lists"}