date.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. // -----
  2. // 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.
  3. //
  4. // 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).
  5. //
  6. // 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.
  7. /*
  8. * Copyright 2010 Matthew Eernisse (mde@fleegix.org)
  9. * and Open Source Applications Foundation
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. *
  23. * Credits: Ideas included from incomplete JS implementation of Olson
  24. * parser, "XMLDAte" by Philippe Goetz (philippe.goetz@wanadoo.fr)
  25. *
  26. * Contributions:
  27. * Jan Niehusmann
  28. * Ricky Romero
  29. * Preston Hunt (prestonhunt@gmail.com)
  30. * Dov. B Katz (dov.katz@morganstanley.com)
  31. * Peter Bergström (pbergstr@mac.com)
  32. * Long Ho
  33. */
  34. (function () {
  35. // Standard initialization stuff to make sure the library is
  36. // usable on both client and server (node) side.
  37. var root = this;
  38. var timezoneJS;
  39. if (typeof exports !== 'undefined') {
  40. timezoneJS = exports;
  41. } else {
  42. timezoneJS = root.timezoneJS = {};
  43. }
  44. timezoneJS.VERSION = '1.0.0';
  45. // Grab the ajax library from global context.
  46. // This can be jQuery, Zepto or fleegix.
  47. // You can also specify your own transport mechanism by declaring
  48. // `timezoneJS.timezone.transport` to a `function`. More details will follow
  49. var $ = root.$ || root.jQuery || root.Zepto
  50. , fleegix = root.fleegix
  51. // Declare constant list of days and months. Unfortunately this doesn't leave room for i18n due to the Olson data being in English itself
  52. , DAYS = timezoneJS.Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  53. , MONTHS = timezoneJS.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  54. , SHORT_MONTHS = {}
  55. , SHORT_DAYS = {}
  56. , EXACT_DATE_TIME = {}
  57. , TZ_REGEXP = new RegExp('^[a-zA-Z]+/');
  58. //`{ "Jan": 0, "Feb": 1, "Mar": 2, "Apr": 3, "May": 4, "Jun": 5, "Jul": 6, "Aug": 7, "Sep": 8, "Oct": 9, "Nov": 10, "Dec": 11 }`
  59. for (var i = 0; i < MONTHS.length; i++) {
  60. SHORT_MONTHS[MONTHS[i].substr(0, 3)] = i;
  61. }
  62. //`{ "Sun": 0, "Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5, "Sat": 6 }`
  63. for (i = 0; i < DAYS.length; i++) {
  64. SHORT_DAYS[DAYS[i].substr(0, 3)] = i;
  65. }
  66. //Handle array indexOf in IE
  67. if (!Array.prototype.indexOf) {
  68. Array.prototype.indexOf = function (el) {
  69. for (var i = 0; i < this.length; i++ ) {
  70. if (el === this[i]) return i;
  71. }
  72. return -1;
  73. }
  74. }
  75. // Format a number to the length = digits. For ex:
  76. //
  77. // `_fixWidth(2, 2) = '02'`
  78. //
  79. // `_fixWidth(1998, 2) = '98'`
  80. //
  81. // This is used to pad numbers in converting date to string in ISO standard.
  82. var _fixWidth = function (number, digits) {
  83. if (typeof number !== "number") { throw "not a number: " + number; }
  84. var s = number.toString();
  85. if (number.length > digits) {
  86. return number.substr(number.length - digits, number.length);
  87. }
  88. while (s.length < digits) {
  89. s = '0' + s;
  90. }
  91. return s;
  92. };
  93. // Abstraction layer for different transport layers, including fleegix/jQuery/Zepto
  94. //
  95. // Object `opts` include
  96. //
  97. // - `url`: url to ajax query
  98. //
  99. // - `async`: true for asynchronous, false otherwise. If false, return value will be response from URL. This is true by default
  100. //
  101. // - `success`: success callback function
  102. //
  103. // - `error`: error callback function
  104. // Returns response from URL if async is false, otherwise the AJAX request object itself
  105. var _transport = function (opts) {
  106. if ((!fleegix || typeof fleegix.xhr === 'undefined') && (!$ || typeof $.ajax === 'undefined')) {
  107. throw new Error('Please use the Fleegix.js XHR module, jQuery ajax, Zepto ajax, or define your own transport mechanism for downloading zone files.');
  108. }
  109. if (!opts) return;
  110. if (!opts.url) throw new Error ('URL must be specified');
  111. if (!('async' in opts)) opts.async = true;
  112. if (!opts.async) {
  113. return fleegix && fleegix.xhr
  114. ? fleegix.xhr.doReq({ url: opts.url, async: false })
  115. : $.ajax({ url : opts.url, async : false }).responseText;
  116. }
  117. return fleegix && fleegix.xhr
  118. ? fleegix.xhr.send({
  119. url : opts.url,
  120. method : 'get',
  121. handleSuccess : opts.success,
  122. handleErr : opts.error
  123. })
  124. : $.ajax({
  125. url : opts.url,
  126. dataType: 'text',
  127. method : 'GET',
  128. error : opts.error,
  129. success : opts.success
  130. });
  131. };
  132. // Constructor, which is similar to that of the native Date object itself
  133. timezoneJS.Date = function () {
  134. var args = Array.prototype.slice.apply(arguments)
  135. , dt = null
  136. , tz = null
  137. , arr = [];
  138. //We support several different constructors, including all the ones from `Date` object
  139. // with a timezone string at the end.
  140. //
  141. //- `[tz]`: Returns object with time in `tz` specified.
  142. //
  143. // - `utcMillis`, `[tz]`: Return object with UTC time = `utcMillis`, in `tz`.
  144. //
  145. // - `Date`, `[tz]`: Returns object with UTC time = `Date.getTime()`, in `tz`.
  146. //
  147. // - `year, month, [date,] [hours,] [minutes,] [seconds,] [millis,] [tz]: Same as `Date` object
  148. // with tz.
  149. //
  150. // - `Array`: Can be any combo of the above.
  151. //
  152. //If 1st argument is an array, we can use it as a list of arguments itself
  153. if (Object.prototype.toString.call(args[0]) === '[object Array]') {
  154. args = args[0];
  155. }
  156. if (typeof args[args.length - 1] === 'string' && TZ_REGEXP.test(args[args.length - 1])) {
  157. tz = args.pop();
  158. }
  159. switch (args.length) {
  160. case 0:
  161. dt = new Date();
  162. break;
  163. case 1:
  164. dt = new Date(args[0]);
  165. break;
  166. default:
  167. for (var i = 0; i < 7; i++) {
  168. arr[i] = args[i] || 0;
  169. }
  170. dt = new Date(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6]);
  171. break;
  172. }
  173. this._useCache = false;
  174. this._tzInfo = {};
  175. this._day = 0;
  176. this.year = 0;
  177. this.month = 0;
  178. this.date = 0;
  179. this.hours = 0;
  180. this.minutes = 0;
  181. this.seconds = 0;
  182. this.milliseconds = 0;
  183. this.timezone = tz || null;
  184. //Tricky part:
  185. // For the cases where there are 1/2 arguments: `timezoneJS.Date(millis, [tz])` and `timezoneJS.Date(Date, [tz])`. The
  186. // Date `dt` created should be in UTC. Thus the way I detect such cases is to determine if `arr` is not populated & `tz`
  187. // is specified. Because if `tz` is not specified, `dt` can be in local time.
  188. if (arr.length) {
  189. this.setFromDateObjProxy(dt);
  190. } else {
  191. this.setFromTimeProxy(dt.getTime(), tz);
  192. }
  193. };
  194. // Implements most of the native Date object
  195. timezoneJS.Date.prototype = {
  196. getDate: function () { return this.date; },
  197. getDay: function () { return this._day; },
  198. getFullYear: function () { return this.year; },
  199. getMonth: function () { return this.month; },
  200. getYear: function () { return this.year; },
  201. getHours: function () { return this.hours; },
  202. getMilliseconds: function () { return this.milliseconds; },
  203. getMinutes: function () { return this.minutes; },
  204. getSeconds: function () { return this.seconds; },
  205. getUTCDate: function () { return this.getUTCDateProxy().getUTCDate(); },
  206. getUTCDay: function () { return this.getUTCDateProxy().getUTCDay(); },
  207. getUTCFullYear: function () { return this.getUTCDateProxy().getUTCFullYear(); },
  208. getUTCHours: function () { return this.getUTCDateProxy().getUTCHours(); },
  209. getUTCMilliseconds: function () { return this.getUTCDateProxy().getUTCMilliseconds(); },
  210. getUTCMinutes: function () { return this.getUTCDateProxy().getUTCMinutes(); },
  211. getUTCMonth: function () { return this.getUTCDateProxy().getUTCMonth(); },
  212. getUTCSeconds: function () { return this.getUTCDateProxy().getUTCSeconds(); },
  213. // Time adjusted to user-specified timezone
  214. getTime: function () {
  215. return this._timeProxy + (this.getTimezoneOffset() * 60 * 1000);
  216. },
  217. getTimezone: function () { return this.timezone; },
  218. getTimezoneOffset: function () { return this.getTimezoneInfo().tzOffset; },
  219. getTimezoneAbbreviation: function () { return this.getTimezoneInfo().tzAbbr; },
  220. getTimezoneInfo: function () {
  221. if (this._useCache) return this._tzInfo;
  222. var res;
  223. // If timezone is specified, get the correct timezone info based on the Date given
  224. if (this.timezone) {
  225. res = this.timezone === 'Etc/UTC' || this.timezone === 'Etc/GMT'
  226. ? { tzOffset: 0, tzAbbr: 'UTC' }
  227. : timezoneJS.timezone.getTzInfo(this._timeProxy, this.timezone);
  228. }
  229. // If no timezone was specified, use the local browser offset
  230. else {
  231. res = { tzOffset: this.getLocalOffset(), tzAbbr: null };
  232. }
  233. this._tzInfo = res;
  234. this._useCache = true;
  235. return res
  236. },
  237. getUTCDateProxy: function () {
  238. var dt = new Date(this._timeProxy);
  239. dt.setUTCMinutes(dt.getUTCMinutes() + this.getTimezoneOffset());
  240. return dt;
  241. },
  242. setDate: function (n) { this.setAttribute('date', n); },
  243. setFullYear: function (n) { this.setAttribute('year', n); },
  244. setMonth: function (n) { this.setAttribute('month', n); },
  245. setYear: function (n) { this.setUTCAttribute('year', n); },
  246. setHours: function (n) { this.setAttribute('hours', n); },
  247. setMilliseconds: function (n) { this.setAttribute('milliseconds', n); },
  248. setMinutes: function (n) { this.setAttribute('minutes', n); },
  249. setSeconds: function (n) { this.setAttribute('seconds', n); },
  250. setTime: function (n) {
  251. if (isNaN(n)) { throw new Error('Units must be a number.'); }
  252. this.setFromTimeProxy(n, this.timezone);
  253. },
  254. setUTCDate: function (n) { this.setUTCAttribute('date', n); },
  255. setUTCFullYear: function (n) { this.setUTCAttribute('year', n); },
  256. setUTCHours: function (n) { this.setUTCAttribute('hours', n); },
  257. setUTCMilliseconds: function (n) { this.setUTCAttribute('milliseconds', n); },
  258. setUTCMinutes: function (n) { this.setUTCAttribute('minutes', n); },
  259. setUTCMonth: function (n) { this.setUTCAttribute('month', n); },
  260. setUTCSeconds: function (n) { this.setUTCAttribute('seconds', n); },
  261. setFromDateObjProxy: function (dt) {
  262. this.year = dt.getFullYear();
  263. this.month = dt.getMonth();
  264. this.date = dt.getDate();
  265. this.hours = dt.getHours();
  266. this.minutes = dt.getMinutes();
  267. this.seconds = dt.getSeconds();
  268. this.milliseconds = dt.getMilliseconds();
  269. this._day = dt.getDay();
  270. this._dateProxy = dt;
  271. this._timeProxy = Date.UTC(this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.milliseconds);
  272. this._useCache = false;
  273. },
  274. setFromTimeProxy: function (utcMillis, tz) {
  275. var dt = new Date(utcMillis);
  276. var tzOffset;
  277. tzOffset = tz ? timezoneJS.timezone.getTzInfo(dt, tz).tzOffset : dt.getTimezoneOffset();
  278. dt.setTime(utcMillis + (dt.getTimezoneOffset() - tzOffset) * 60000);
  279. this.setFromDateObjProxy(dt);
  280. },
  281. setAttribute: function (unit, n) {
  282. if (isNaN(n)) { throw new Error('Units must be a number.'); }
  283. var dt = this._dateProxy;
  284. var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
  285. dt['set' + meth](n);
  286. this.setFromDateObjProxy(dt);
  287. },
  288. setUTCAttribute: function (unit, n) {
  289. if (isNaN(n)) { throw new Error('Units must be a number.'); }
  290. var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
  291. var dt = this.getUTCDateProxy();
  292. dt['setUTC' + meth](n);
  293. dt.setUTCMinutes(dt.getUTCMinutes() - this.getTimezoneOffset());
  294. this.setFromTimeProxy(dt.getTime() + this.getTimezoneOffset() * 60000, this.timezone);
  295. },
  296. setTimezone: function (tz) {
  297. var previousOffset = this.getTimezoneInfo().tzOffset;
  298. this.timezone = tz;
  299. this._useCache = false;
  300. // Set UTC minutes offsets by the delta of the two timezones
  301. this.setUTCMinutes(this.getUTCMinutes() - this.getTimezoneInfo().tzOffset + previousOffset);
  302. },
  303. removeTimezone: function () {
  304. this.timezone = null;
  305. this._useCache = false;
  306. },
  307. valueOf: function () { return this.getTime(); },
  308. clone: function () {
  309. return this.timezone ? new timezoneJS.Date(this.getTime(), this.timezone) : new timezoneJS.Date(this.getTime());
  310. },
  311. toGMTString: function () { return this.toString('EEE, dd MMM yyyy HH:mm:ss Z', 'Etc/GMT'); },
  312. toLocaleString: function () {},
  313. toLocaleDateString: function () {},
  314. toLocaleTimeString: function () {},
  315. toSource: function () {},
  316. toISOString: function () { return this.toString('yyyy-MM-ddTHH:mm:ss.SSS', 'Etc/UTC') + 'Z'; },
  317. toJSON: function () { return this.toISOString(); },
  318. // Allows different format following ISO8601 format:
  319. toString: function (format, tz) {
  320. // Default format is the same as toISOString
  321. if (!format) format = 'yyyy-MM-dd HH:mm:ss';
  322. var result = format;
  323. var tzInfo = tz ? timezoneJS.timezone.getTzInfo(this.getTime(), tz) : this.getTimezoneInfo();
  324. var _this = this;
  325. // If timezone is specified, get a clone of the current Date object and modify it
  326. if (tz) {
  327. _this = this.clone();
  328. _this.setTimezone(tz);
  329. }
  330. var hours = _this.getHours();
  331. return result
  332. // fix the same characters in Month names
  333. .replace(/a+/g, function () { return 'k'; })
  334. // `y`: year
  335. .replace(/y+/g, function (token) { return _fixWidth(_this.getFullYear(), token.length); })
  336. // `d`: date
  337. .replace(/d+/g, function (token) { return _fixWidth(_this.getDate(), token.length); })
  338. // `m`: minute
  339. .replace(/m+/g, function (token) { return _fixWidth(_this.getMinutes(), token.length); })
  340. // `s`: second
  341. .replace(/s+/g, function (token) { return _fixWidth(_this.getSeconds(), token.length); })
  342. // `S`: millisecond
  343. .replace(/S+/g, function (token) { return _fixWidth(_this.getMilliseconds(), token.length); })
  344. // `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)
  345. .replace(/M+/g, function (token) {
  346. var _month = _this.getMonth(),
  347. _len = token.length;
  348. if (_len > 3) {
  349. return timezoneJS.Months[_month];
  350. } else if (_len > 2) {
  351. return timezoneJS.Months[_month].substring(0, _len);
  352. }
  353. return _fixWidth(_month + 1, _len);
  354. })
  355. // `k`: AM/PM
  356. .replace(/k+/g, function () {
  357. if (hours >= 12) {
  358. if (hours > 12) {
  359. hours -= 12;
  360. }
  361. return 'PM';
  362. }
  363. return 'AM';
  364. })
  365. // `H`: hour
  366. .replace(/H+/g, function (token) { return _fixWidth(hours, token.length); })
  367. // `E`: day
  368. .replace(/E+/g, function (token) { return DAYS[_this.getDay()].substring(0, token.length); })
  369. // `Z`: timezone abbreviation
  370. .replace(/Z+/gi, function () { return tzInfo.tzAbbr; });
  371. },
  372. toUTCString: function () { return this.toGMTString(); },
  373. civilToJulianDayNumber: function (y, m, d) {
  374. var a;
  375. // Adjust for zero-based JS-style array
  376. m++;
  377. if (m > 12) {
  378. a = parseInt(m/12, 10);
  379. m = m % 12;
  380. y += a;
  381. }
  382. if (m <= 2) {
  383. y -= 1;
  384. m += 12;
  385. }
  386. a = Math.floor(y / 100);
  387. var b = 2 - a + Math.floor(a / 4)
  388. , jDt = Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d + b - 1524;
  389. return jDt;
  390. },
  391. getLocalOffset: function () {
  392. return this._dateProxy.getTimezoneOffset();
  393. }
  394. };
  395. timezoneJS.timezone = new function () {
  396. var _this = this
  397. , 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'}
  398. , 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'};
  399. function invalidTZError(t) { throw new Error('Timezone "' + t + '" is either incorrect, or not loaded in the timezone registry.'); }
  400. function builtInLoadZoneFile(fileName, opts) {
  401. var url = _this.zoneFileBasePath + '/' + fileName;
  402. return !opts || !opts.async
  403. ? _this.parseZones(_this.transport({ url : url, async : false }))
  404. : _this.transport({
  405. async: true,
  406. url : url,
  407. success : function (str) {
  408. if (_this.parseZones(str) && typeof opts.callback === 'function') {
  409. opts.callback();
  410. }
  411. return true;
  412. },
  413. error : function () {
  414. throw new Error('Error retrieving "' + url + '" zoneinfo files');
  415. }
  416. });
  417. }
  418. function getRegionForTimezone(tz) {
  419. var exc = regionExceptions[tz]
  420. , reg
  421. , ret;
  422. if (exc) return exc;
  423. reg = tz.split('/')[0];
  424. ret = regionMap[reg];
  425. // If there's nothing listed in the main regions for this TZ, check the 'backward' links
  426. if (ret) return ret;
  427. var link = _this.zones[tz];
  428. if (typeof link === 'string') {
  429. return getRegionForTimezone(link);
  430. }
  431. // Backward-compat file hasn't loaded yet, try looking in there
  432. if (!_this.loadedZones.backward) {
  433. // This is for obvious legacy zones (e.g., Iceland) that don't even have a prefix like "America/" that look like normal zones
  434. _this.loadZoneFile('backward');
  435. return getRegionForTimezone(tz);
  436. }
  437. invalidTZError(tz);
  438. }
  439. function parseTimeString(str) {
  440. var pat = /(\d+)(?::0*(\d*))?(?::0*(\d*))?([wsugz])?$/;
  441. var hms = str.match(pat);
  442. hms[1] = parseInt(hms[1], 10);
  443. hms[2] = hms[2] ? parseInt(hms[2], 10) : 0;
  444. hms[3] = hms[3] ? parseInt(hms[3], 10) : 0;
  445. return hms;
  446. }
  447. function processZone(z) {
  448. if (!z[3]) { return; }
  449. var yea = parseInt(z[3], 10);
  450. var mon = 11;
  451. var dat = 31;
  452. if (z[4]) {
  453. mon = SHORT_MONTHS[z[4].substr(0, 3)];
  454. dat = parseInt(z[5], 10) || 1;
  455. }
  456. var string = z[6] ? z[6] : '00:00:00'
  457. , t = parseTimeString(string);
  458. return [yea, mon, dat, t[1], t[2], t[3]];
  459. }
  460. function getZone(dt, tz) {
  461. var utcMillis = typeof dt === 'number' ? dt : new Date(dt).getTime();
  462. var t = tz;
  463. var zoneList = _this.zones[t];
  464. // Follow links to get to an actual zone
  465. while (typeof zoneList === "string") {
  466. t = zoneList;
  467. zoneList = _this.zones[t];
  468. }
  469. if (!zoneList) {
  470. // Backward-compat file hasn't loaded yet, try looking in there
  471. if (!_this.loadedZones.backward) {
  472. //This is for backward entries like "America/Fort_Wayne" that
  473. // getRegionForTimezone *thinks* it has a region file and zone
  474. // for (e.g., America => 'northamerica'), but in reality it's a
  475. // legacy zone we need the backward file for.
  476. _this.loadZoneFile('backward');
  477. return getZone(dt, tz);
  478. }
  479. invalidTZError(t);
  480. }
  481. if (zoneList.length === 0) {
  482. throw new Error('No Zone found for "' + tz + '" on ' + dt);
  483. }
  484. //Do backwards lookup since most use cases deal with newer dates.
  485. for (var i = zoneList.length - 1; i >= 0; i--) {
  486. var z = zoneList[i];
  487. if (z[3] && utcMillis > z[3]) break;
  488. }
  489. return zoneList[i+1];
  490. }
  491. function getBasicOffset(time) {
  492. var off = parseTimeString(time)
  493. , adj = time.indexOf('-') === 0 ? -1 : 1;
  494. off = adj * (((off[1] * 60 + off[2]) * 60 + off[3]) * 1000);
  495. return off/60/1000;
  496. }
  497. //if isUTC is true, date is given in UTC, otherwise it's given
  498. // in local time (ie. date.getUTC*() returns local time components)
  499. function getRule(dt, zone, isUTC) {
  500. var date = typeof dt === 'number' ? new Date(dt) : dt;
  501. var ruleset = zone[1];
  502. var basicOffset = zone[0];
  503. //Convert a date to UTC. Depending on the 'type' parameter, the date
  504. // parameter may be:
  505. //
  506. // - `u`, `g`, `z`: already UTC (no adjustment).
  507. //
  508. // - `s`: standard time (adjust for time zone offset but not for DST)
  509. //
  510. // - `w`: wall clock time (adjust for both time zone and DST offset).
  511. //
  512. // DST adjustment is done using the rule given as third argument.
  513. var convertDateToUTC = function (date, type, rule) {
  514. var offset = 0;
  515. if (type === 'u' || type === 'g' || type === 'z') { // UTC
  516. offset = 0;
  517. } else if (type === 's') { // Standard Time
  518. offset = basicOffset;
  519. } else if (type === 'w' || !type) { // Wall Clock Time
  520. offset = getAdjustedOffset(basicOffset, rule);
  521. } else {
  522. throw("unknown type " + type);
  523. }
  524. offset *= 60 * 1000; // to millis
  525. return new Date(date.getTime() + offset);
  526. };
  527. //Step 1: Find applicable rules for this year.
  528. //
  529. //Step 2: Sort the rules by effective date.
  530. //
  531. //Step 3: Check requested date to see if a rule has yet taken effect this year. If not,
  532. //
  533. //Step 4: Get the rules for the previous year. If there isn't an applicable rule for last year, then
  534. // there probably is no current time offset since they seem to explicitly turn off the offset
  535. // when someone stops observing DST.
  536. //
  537. // FIXME if this is not the case and we'll walk all the way back (ugh).
  538. //
  539. //Step 5: Sort the rules by effective date.
  540. //Step 6: Apply the most recent rule before the current time.
  541. var convertRuleToExactDateAndTime = function (yearAndRule, prevRule) {
  542. var year = yearAndRule[0]
  543. , rule = yearAndRule[1];
  544. // Assume that the rule applies to the year of the given date.
  545. var hms = rule[5];
  546. var effectiveDate;
  547. if (!EXACT_DATE_TIME[year])
  548. EXACT_DATE_TIME[year] = {};
  549. // Result for given parameters is already stored
  550. if (EXACT_DATE_TIME[year][rule])
  551. effectiveDate = EXACT_DATE_TIME[year][rule];
  552. else {
  553. //If we have a specific date, use that!
  554. if (!isNaN(rule[4])) {
  555. effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4], hms[1], hms[2], hms[3], 0));
  556. }
  557. //Let's hunt for the date.
  558. else {
  559. var targetDay
  560. , operator;
  561. //Example: `lastThu`
  562. if (rule[4].substr(0, 4) === "last") {
  563. // Start at the last day of the month and work backward.
  564. effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]] + 1, 1, hms[1] - 24, hms[2], hms[3], 0));
  565. targetDay = SHORT_DAYS[rule[4].substr(4, 3)];
  566. operator = "<=";
  567. }
  568. //Example: `Sun>=15`
  569. else {
  570. //Start at the specified date.
  571. effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4].substr(5), hms[1], hms[2], hms[3], 0));
  572. targetDay = SHORT_DAYS[rule[4].substr(0, 3)];
  573. operator = rule[4].substr(3, 2);
  574. }
  575. var ourDay = effectiveDate.getUTCDay();
  576. //Go forwards.
  577. if (operator === ">=") {
  578. effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay + ((targetDay < ourDay) ? 7 : 0)));
  579. }
  580. //Go backwards. Looking for the last of a certain day, or operator is "<=" (less likely).
  581. else {
  582. effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay - ((targetDay > ourDay) ? 7 : 0)));
  583. }
  584. }
  585. EXACT_DATE_TIME[year][rule] = effectiveDate;
  586. }
  587. //If previous rule is given, correct for the fact that the starting time of the current
  588. // rule may be specified in local time.
  589. if (prevRule) {
  590. effectiveDate = convertDateToUTC(effectiveDate, hms[4], prevRule);
  591. }
  592. return effectiveDate;
  593. };
  594. var findApplicableRules = function (year, ruleset) {
  595. var applicableRules = [];
  596. for (var i = 0; ruleset && i < ruleset.length; i++) {
  597. //Exclude future rules.
  598. if (ruleset[i][0] <= year &&
  599. (
  600. // Date is in a set range.
  601. ruleset[i][1] >= year ||
  602. // Date is in an "only" year.
  603. (ruleset[i][0] === year && ruleset[i][1] === "only") ||
  604. //We're in a range from the start year to infinity.
  605. ruleset[i][1] === "max"
  606. )
  607. ) {
  608. //It's completely okay to have any number of matches here.
  609. // Normally we should only see two, but that doesn't preclude other numbers of matches.
  610. // These matches are applicable to this year.
  611. applicableRules.push([year, ruleset[i]]);
  612. }
  613. }
  614. return applicableRules;
  615. };
  616. var compareDates = function (a, b, prev) {
  617. var year, rule;
  618. if (a.constructor !== Date) {
  619. year = a[0];
  620. rule = a[1];
  621. a = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule])
  622. ? EXACT_DATE_TIME[year][rule]
  623. : convertRuleToExactDateAndTime(a, prev);
  624. } else if (prev) {
  625. a = convertDateToUTC(a, isUTC ? 'u' : 'w', prev);
  626. }
  627. if (b.constructor !== Date) {
  628. year = b[0];
  629. rule = b[1];
  630. b = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule]) ? EXACT_DATE_TIME[year][rule]
  631. : convertRuleToExactDateAndTime(b, prev);
  632. } else if (prev) {
  633. b = convertDateToUTC(b, isUTC ? 'u' : 'w', prev);
  634. }
  635. a = Number(a);
  636. b = Number(b);
  637. return a - b;
  638. };
  639. var year = date.getUTCFullYear();
  640. var applicableRules;
  641. applicableRules = findApplicableRules(year, _this.rules[ruleset]);
  642. applicableRules.push(date);
  643. //While sorting, the time zone in which the rule starting time is specified
  644. // is ignored. This is ok as long as the timespan between two DST changes is
  645. // larger than the DST offset, which is probably always true.
  646. // As the given date may indeed be close to a DST change, it may get sorted
  647. // to a wrong position (off by one), which is corrected below.
  648. applicableRules.sort(compareDates);
  649. //If there are not enough past DST rules...
  650. if (applicableRules.indexOf(date) < 2) {
  651. applicableRules = applicableRules.concat(findApplicableRules(year-1, _this.rules[ruleset]));
  652. applicableRules.sort(compareDates);
  653. }
  654. var pinpoint = applicableRules.indexOf(date);
  655. if (pinpoint > 1 && compareDates(date, applicableRules[pinpoint-1], applicableRules[pinpoint-2][1]) < 0) {
  656. //The previous rule does not really apply, take the one before that.
  657. return applicableRules[pinpoint - 2][1];
  658. } else if (pinpoint > 0 && pinpoint < applicableRules.length - 1 && compareDates(date, applicableRules[pinpoint+1], applicableRules[pinpoint-1][1]) > 0) {
  659. //The next rule does already apply, take that one.
  660. return applicableRules[pinpoint + 1][1];
  661. } else if (pinpoint === 0) {
  662. //No applicable rule found in this and in previous year.
  663. return null;
  664. }
  665. return applicableRules[pinpoint - 1][1];
  666. }
  667. function getAdjustedOffset(off, rule) {
  668. return -Math.ceil(rule[6] - off);
  669. }
  670. function getAbbreviation(zone, rule) {
  671. var res;
  672. var base = zone[2];
  673. if (base.indexOf('%s') > -1) {
  674. var repl;
  675. if (rule) {
  676. repl = rule[7] === '-' ? '' : rule[7];
  677. }
  678. //FIXME: Right now just falling back to Standard --
  679. // apparently ought to use the last valid rule,
  680. // although in practice that always ought to be Standard
  681. else {
  682. repl = 'S';
  683. }
  684. res = base.replace('%s', repl);
  685. }
  686. else if (base.indexOf('/') > -1) {
  687. //Chose one of two alternative strings.
  688. res = base.split("/", 2)[rule[6] ? 1 : 0];
  689. } else {
  690. res = base;
  691. }
  692. return res;
  693. }
  694. this.zoneFileBasePath;
  695. this.zoneFiles = ['africa', 'antarctica', 'asia', 'australasia', 'backward', 'etcetera', 'europe', 'northamerica', 'pacificnew', 'southamerica'];
  696. this.loadingSchemes = {
  697. PRELOAD_ALL: 'preloadAll',
  698. LAZY_LOAD: 'lazyLoad',
  699. MANUAL_LOAD: 'manualLoad'
  700. };
  701. this.loadingScheme = this.loadingSchemes.LAZY_LOAD;
  702. this.loadedZones = {};
  703. this.zones = {};
  704. this.rules = {};
  705. this.init = function (o) {
  706. var opts = { async: true }
  707. , def = this.defaultZoneFile = this.loadingScheme === this.loadingSchemes.PRELOAD_ALL
  708. ? this.zoneFiles
  709. : 'northamerica'
  710. , done = 0
  711. , callbackFn;
  712. //Override default with any passed-in opts
  713. for (var p in o) {
  714. opts[p] = o[p];
  715. }
  716. if (typeof def === 'string') {
  717. return this.loadZoneFile(def, opts);
  718. }
  719. //Wraps callback function in another one that makes
  720. // sure all files have been loaded.
  721. callbackFn = opts.callback;
  722. opts.callback = function () {
  723. done++;
  724. (done === def.length) && typeof callbackFn === 'function' && callbackFn();
  725. };
  726. for (var i = 0; i < def.length; i++) {
  727. this.loadZoneFile(def[i], opts);
  728. }
  729. };
  730. //Get the zone files via XHR -- if the sync flag
  731. // is set to true, it's being called by the lazy-loading
  732. // mechanism, so the result needs to be returned inline.
  733. this.loadZoneFile = function (fileName, opts) {
  734. if (typeof this.zoneFileBasePath === 'undefined') {
  735. throw new Error('Please define a base path to your zone file directory -- timezoneJS.timezone.zoneFileBasePath.');
  736. }
  737. //Ignore already loaded zones.
  738. if (this.loadedZones[fileName]) {
  739. return;
  740. }
  741. this.loadedZones[fileName] = true;
  742. return builtInLoadZoneFile(fileName, opts);
  743. };
  744. this.loadZoneJSONData = function (url, sync) {
  745. var processData = function (data) {
  746. data = eval('('+ data +')');
  747. for (var z in data.zones) {
  748. _this.zones[z] = data.zones[z];
  749. }
  750. for (var r in data.rules) {
  751. _this.rules[r] = data.rules[r];
  752. }
  753. };
  754. return sync
  755. ? processData(_this.transport({ url : url, async : false }))
  756. : _this.transport({ url : url, success : processData });
  757. };
  758. this.loadZoneDataFromObject = function (data) {
  759. if (!data) { return; }
  760. for (var z in data.zones) {
  761. _this.zones[z] = data.zones[z];
  762. }
  763. for (var r in data.rules) {
  764. _this.rules[r] = data.rules[r];
  765. }
  766. };
  767. this.getAllZones = function () {
  768. var arr = [];
  769. for (var z in this.zones) { arr.push(z); }
  770. return arr.sort();
  771. };
  772. this.parseZones = function (str) {
  773. var lines = str.split('\n')
  774. , arr = []
  775. , chunk = ''
  776. , l
  777. , zone = null
  778. , rule = null;
  779. for (var i = 0; i < lines.length; i++) {
  780. l = lines[i];
  781. if (l.match(/^\s/)) {
  782. l = "Zone " + zone + l;
  783. }
  784. l = l.split("#")[0];
  785. if (l.length > 3) {
  786. arr = l.split(/\s+/);
  787. chunk = arr.shift();
  788. //Ignore Leap.
  789. switch (chunk) {
  790. case 'Zone':
  791. zone = arr.shift();
  792. if (!_this.zones[zone]) {
  793. _this.zones[zone] = [];
  794. }
  795. if (arr.length < 3) break;
  796. //Process zone right here and replace 3rd element with the processed array.
  797. arr.splice(3, arr.length, processZone(arr));
  798. if (arr[3]) arr[3] = Date.UTC.apply(null, arr[3]);
  799. arr[0] = -getBasicOffset(arr[0]);
  800. _this.zones[zone].push(arr);
  801. break;
  802. case 'Rule':
  803. rule = arr.shift();
  804. if (!_this.rules[rule]) {
  805. _this.rules[rule] = [];
  806. }
  807. //Parse int FROM year and TO year
  808. arr[0] = parseInt(arr[0], 10);
  809. arr[1] = parseInt(arr[1], 10) || arr[1];
  810. //Parse time string AT
  811. arr[5] = parseTimeString(arr[5]);
  812. //Parse offset SAVE
  813. arr[6] = getBasicOffset(arr[6]);
  814. _this.rules[rule].push(arr);
  815. break;
  816. case 'Link':
  817. //No zones for these should already exist.
  818. if (_this.zones[arr[1]]) {
  819. throw new Error('Error with Link ' + arr[1] + '. Cannot create link of a preexisted zone.');
  820. }
  821. //Create the link.
  822. _this.zones[arr[1]] = arr[0];
  823. break;
  824. }
  825. }
  826. }
  827. return true;
  828. };
  829. //Expose transport mechanism and allow overwrite.
  830. this.transport = _transport;
  831. this.getTzInfo = function (dt, tz, isUTC) {
  832. //Lazy-load any zones not yet loaded.
  833. if (this.loadingScheme === this.loadingSchemes.LAZY_LOAD) {
  834. //Get the correct region for the zone.
  835. var zoneFile = getRegionForTimezone(tz);
  836. if (!zoneFile) {
  837. throw new Error('Not a valid timezone ID.');
  838. }
  839. if (!this.loadedZones[zoneFile]) {
  840. //Get the file and parse it -- use synchronous XHR.
  841. this.loadZoneFile(zoneFile);
  842. }
  843. }
  844. var z = getZone(dt, tz);
  845. var off = z[0];
  846. //See if the offset needs adjustment.
  847. var rule = getRule(dt, z, isUTC);
  848. if (rule) {
  849. off = getAdjustedOffset(off, rule);
  850. }
  851. var abbr = getAbbreviation(z, rule);
  852. return { tzOffset: off, tzAbbr: abbr };
  853. };
  854. };
  855. }).call(this);