timezone.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojox.date.timezone"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.date.timezone"] = true;
  8. /******************************************************************************
  9. * Dojo port of fleegix date plugin from
  10. *
  11. * http://js.fleegix.org/plugins/date/date
  12. *
  13. * contributed to Dojo under CLA, with thanks to Matthew Eernisse (mde@fleegix.org)
  14. * and Open Source Applications Foundation
  15. *
  16. * Credits: Ideas included from incomplete JS implementation of Olson
  17. * parser, "XMLDate" by Philippe Goetz (philippe.goetz@wanadoo.fr)
  18. *****************************************************************************/
  19. dojo.experimental("dojox.date.timezone");
  20. dojo.provide("dojox.date.timezone");
  21. dojo.require("dojo.date.locale");
  22. (function(_d){
  23. var cfg = _d.config;
  24. var _zoneFiles = [ "africa", "antarctica", "asia", "australasia", "backward",
  25. "etcetera", "europe", "northamerica", "pacificnew",
  26. "southamerica" ];
  27. // Our mins an maxes for years that we care about
  28. var _minYear = 1835,
  29. _maxYear = 2038;
  30. var _loadedZones = {},
  31. _zones = {},
  32. _loadedRanges = {},
  33. _rules = {};
  34. // timezoneFileBasePath: String
  35. // A different location to pull zone files from
  36. var timezoneFileBasePath = cfg.timezoneFileBasePath ||
  37. _d.moduleUrl("dojox.date", "zoneinfo");
  38. // loadingScheme: String
  39. // One of "preloadAll", "lazyLoad" (Defaults "lazyLoad")
  40. var loadingScheme = cfg.timezoneLoadingScheme || "preloadAll";
  41. // defaultZoneFile: String or String[]
  42. // The default file (or files) to load on startup - other files will
  43. // be lazily-loaded on-demand
  44. var defaultZoneFile = cfg.defaultZoneFile ||
  45. ((loadingScheme == "preloadAll") ? _zoneFiles : "northamerica");
  46. // Set our olson-zoneinfo content handler
  47. _d._contentHandlers["olson-zoneinfo"] = function(xhr){
  48. var str = _d._contentHandlers["text"](xhr);
  49. var s = "";
  50. var lines = str.split("\n");
  51. var arr = [];
  52. var chunk = "";
  53. var zone = null;
  54. var rule = null;
  55. var ret = {zones: {}, rules: {}};
  56. for(var i = 0; i < lines.length; i++){
  57. var l = lines[i];
  58. if(l.match(/^\s/)){
  59. l = "Zone " + zone + l;
  60. }
  61. l = l.split("#")[0];
  62. if(l.length > 3){
  63. arr = l.split(/\s+/);
  64. chunk = arr.shift();
  65. switch(chunk){
  66. case 'Zone':
  67. zone = arr.shift();
  68. if(arr[0]){
  69. // Handle extra commas in the middle of a zone
  70. if(!ret.zones[zone]){ ret.zones[zone] = []; }
  71. ret.zones[zone].push(arr);
  72. }
  73. break;
  74. case 'Rule':
  75. rule = arr.shift();
  76. if(!ret.rules[rule]){ ret.rules[rule] = []; }
  77. ret.rules[rule].push(arr);
  78. break;
  79. case 'Link':
  80. // No zones for these should already exist
  81. if(ret.zones[arr[1]]){
  82. throw new Error('Error with Link ' + arr[1]);
  83. }
  84. // Create the link
  85. ret.zones[arr[1]] = arr[0];
  86. break;
  87. case 'Leap':
  88. break;
  89. default:
  90. // Fail silently
  91. break;
  92. }
  93. }
  94. }
  95. return ret; // Object
  96. };
  97. function loadZoneData(/* Object */ data){
  98. // summary:
  99. // Loads the given data object into the zone database
  100. //
  101. // data: Object
  102. // The data to load - contains "zones" and "rules" parameters
  103. data = data || {};
  104. _zones = _d.mixin(_zones, data.zones||{});
  105. _rules = _d.mixin(_rules, data.rules||{});
  106. }
  107. function errorLoadingZoneFile(e){
  108. console.error("Error loading zone file:", e);
  109. throw e;
  110. }
  111. function loadZoneFile(/* String */ fileName){
  112. // summary:
  113. // Loads the given URL of the Olson zone information into the
  114. // zone database
  115. //
  116. // fileName: String
  117. // The zoneinfo file name to load
  118. // TODO: Maybe behave similar to requireLocalization - rather than
  119. // Using dojo.xhrGet?
  120. _loadedZones[fileName] = true;
  121. _d.xhrGet({
  122. url: timezoneFileBasePath + "/" + fileName,
  123. sync: true, // Needs to be synchronous so we can return values
  124. handleAs: "olson-zoneinfo",
  125. load: loadZoneData,
  126. error: errorLoadingZoneFile
  127. });
  128. }
  129. var monthMap = { 'jan': 0, 'feb': 1, 'mar': 2, 'apr': 3,'may': 4, 'jun': 5,
  130. 'jul': 6, 'aug': 7, 'sep': 8, 'oct': 9, 'nov': 10, 'dec': 11 },
  131. dayMap = {'sun': 0, 'mon': 1, 'tue': 2, 'wed': 3, 'thu': 4,
  132. 'fri': 5, 'sat': 6 },
  133. regionMap = {'EST': "northamerica", 'MST': "northamerica",
  134. 'HST': "northamerica", 'EST5EDT': "northamerica",
  135. 'CST6CDT': "northamerica", 'MST7MDT': "northamerica",
  136. 'PST8PDT': "northamerica", 'America': "northamerica",
  137. 'Pacific': "australasia", 'Atlantic': "europe",
  138. 'Africa': "africa", 'Indian': "africa",
  139. 'Antarctica': "antarctica", 'Asia': "asia",
  140. 'Australia': "australasia", 'Europe': "europe",
  141. 'WET': "europe", 'CET': "europe", 'MET': "europe",
  142. 'EET': "europe"},
  143. regionExceptions = {'Pacific/Honolulu':"northamerica",
  144. 'Atlantic/Bermuda':"northamerica",
  145. 'Atlantic/Cape_Verde':"africa",
  146. 'Atlantic/St_Helena':"africa",
  147. 'Indian/Kerguelen':"antarctica",
  148. 'Indian/Chagos':"asia",
  149. 'Indian/Maldives':"asia",
  150. 'Indian/Christmas':"australasia",
  151. 'Indian/Cocos':"australasia",
  152. 'America/Danmarkshavn':"europe",
  153. 'America/Scoresbysund':"europe",
  154. 'America/Godthab':"europe",
  155. 'America/Thule':"europe",
  156. 'Asia/Yekaterinburg':"europe",
  157. 'Asia/Omsk':"europe",
  158. 'Asia/Novosibirsk':"europe",
  159. 'Asia/Krasnoyarsk':"europe",
  160. 'Asia/Irkutsk':"europe",
  161. 'Asia/Yakutsk':"europe",
  162. 'Asia/Vladivostok':"europe",
  163. 'Asia/Sakhalin':"europe",
  164. 'Asia/Magadan':"europe",
  165. 'Asia/Kamchatka':"europe",
  166. 'Asia/Anadyr':"europe",
  167. 'Africa/Ceuta':"europe",
  168. 'America/Argentina/Buenos_Aires':"southamerica",
  169. 'America/Argentina/Cordoba':"southamerica",
  170. 'America/Argentina/Tucuman':"southamerica",
  171. 'America/Argentina/La_Rioja':"southamerica",
  172. 'America/Argentina/San_Juan':"southamerica",
  173. 'America/Argentina/Jujuy':"southamerica",
  174. 'America/Argentina/Catamarca':"southamerica",
  175. 'America/Argentina/Mendoza':"southamerica",
  176. 'America/Argentina/Rio_Gallegos':"southamerica",
  177. 'America/Argentina/Ushuaia':"southamerica",
  178. 'America/Aruba':"southamerica",
  179. 'America/La_Paz':"southamerica",
  180. 'America/Noronha':"southamerica",
  181. 'America/Belem':"southamerica",
  182. 'America/Fortaleza':"southamerica",
  183. 'America/Recife':"southamerica",
  184. 'America/Araguaina':"southamerica",
  185. 'America/Maceio':"southamerica",
  186. 'America/Bahia':"southamerica",
  187. 'America/Sao_Paulo':"southamerica",
  188. 'America/Campo_Grande':"southamerica",
  189. 'America/Cuiaba':"southamerica",
  190. 'America/Porto_Velho':"southamerica",
  191. 'America/Boa_Vista':"southamerica",
  192. 'America/Manaus':"southamerica",
  193. 'America/Eirunepe':"southamerica",
  194. 'America/Rio_Branco':"southamerica",
  195. 'America/Santiago':"southamerica",
  196. 'Pacific/Easter':"southamerica",
  197. 'America/Bogota':"southamerica",
  198. 'America/Curacao':"southamerica",
  199. 'America/Guayaquil':"southamerica",
  200. 'Pacific/Galapagos':"southamerica",
  201. 'Atlantic/Stanley':"southamerica",
  202. 'America/Cayenne':"southamerica",
  203. 'America/Guyana':"southamerica",
  204. 'America/Asuncion':"southamerica",
  205. 'America/Lima':"southamerica",
  206. 'Atlantic/South_Georgia':"southamerica",
  207. 'America/Paramaribo':"southamerica",
  208. 'America/Port_of_Spain':"southamerica",
  209. 'America/Montevideo':"southamerica",
  210. 'America/Caracas':"southamerica"},
  211. abbrExceptions = { 'US': "S", 'Chatham': "S", 'NZ': "S", 'NT_YK': "S",
  212. 'Edm': "S", 'Salv': "S", 'Canada': "S", 'StJohns': "S",
  213. 'TC': "S", 'Guat': "S", 'Mexico': "S", 'Haiti': "S",
  214. 'Barb': "S", 'Belize': "S", 'CR': "S", 'Moncton': "S",
  215. 'Swift': "S", 'Hond': "S", 'Thule': "S", 'NZAQ': "S",
  216. 'Zion': "S", 'ROK': "S", 'PRC': "S", 'Taiwan': "S",
  217. 'Ghana': "GMT", 'SL': "WAT", 'Chicago': "S",
  218. 'Detroit': "S", 'Vanc': "S", 'Denver': "S",
  219. 'Halifax': "S", 'Cuba': "S", 'Indianapolis': "S",
  220. 'Starke': "S", 'Marengo': "S", 'Pike': "S",
  221. 'Perry': "S", 'Vincennes': "S", 'Pulaski': "S",
  222. 'Louisville': "S", 'CA': "S", 'Nic': "S",
  223. 'Menominee': "S", 'Mont': "S", 'Bahamas': "S",
  224. 'NYC': "S", 'Regina': "S", 'Resolute': "ES",
  225. 'DR': "S", 'Toronto': "S", 'Winn': "S" };
  226. function invalidTZError(t) {
  227. throw new Error('Timezone "' + t +
  228. '" is either incorrect, or not loaded in the timezone registry.');
  229. }
  230. function getRegionForTimezone(/* String */ tz) {
  231. // summary:
  232. // Returns the Olson region for the given timezone
  233. var ret = regionExceptions[tz];
  234. if(!ret){
  235. var reg = tz.split('/')[0];
  236. ret = regionMap[reg];
  237. // If there's nothing listed in the main regions for
  238. // this TZ, check the 'backward' links
  239. if(!ret){
  240. var link = _zones[tz];
  241. if(typeof link == 'string'){
  242. return getRegionForTimezone(link); // String
  243. }else{
  244. // Backward-compat file hasn't loaded yet, try looking in there
  245. if (!_loadedZones.backward) {
  246. // This is for obvious legacy zones (e.g., Iceland) that
  247. // don't even have a prefix like "America/" that look like
  248. // normal zones
  249. loadZoneFile("backward");
  250. return getRegionForTimezone(tz); // String
  251. }else{
  252. invalidTZError(tz);
  253. }
  254. }
  255. }
  256. }
  257. return ret; // String
  258. }
  259. function parseTimeString(/* String */ str) {
  260. // summary:
  261. // Parses the given time string and returns it as an integer array
  262. var pat = /(\d+)(?::0*(\d*))?(?::0*(\d*))?([su])?$/;
  263. var hms = str.match(pat);
  264. if(!hms){
  265. return null;
  266. }
  267. hms[1] = parseInt(hms[1], 10);
  268. hms[2] = hms[2] ? parseInt(hms[2], 10) : 0;
  269. hms[3] = hms[3] ? parseInt(hms[3], 10) : 0;
  270. return hms; // int[]
  271. }
  272. function getUTCStamp(/* int */ y, /* int */ m, /* int */ d, /* int */ h,
  273. /* int */ mn, /* int */ s, /* int? */ off){
  274. // summary:
  275. // Returns the UTC timestamp, adjusted by the given (optional) offset
  276. return Date.UTC(y, m, d, h, mn, s) + ((off||0) * 60 * 1000);
  277. }
  278. function getMonthNumber(/* String */ m){
  279. // summary:
  280. // Returns the javascript month number for the given string
  281. return monthMap[m.substr(0, 3).toLowerCase()];
  282. }
  283. function getOffsetInMins(/* String */ str){
  284. // summary:
  285. // Returns the offset value represented by the string, in minutes
  286. var off = parseTimeString(str);
  287. if(off === null){ return 0; }
  288. var adj = str.indexOf('-') === 0 ? -1 : 1;
  289. off = adj * (((off[1] * 60 + off[2]) *60 + off[3]) * 1000);
  290. return -off/60/1000;
  291. }
  292. function _getRuleStart(/* Rule */ rule, /* int */ year, /* int */ off){
  293. // summary:
  294. // Returns a date that the rule begins matching in the given year.
  295. var month = getMonthNumber(rule[3]),
  296. day = rule[4],
  297. time = parseTimeString(rule[5]);
  298. if(time[4] == "u"){
  299. // We are UTC - so there is no offset to use
  300. off = 0;
  301. }
  302. var d, dtDay, incr;
  303. if(isNaN(day)){
  304. if(day.substr(0, 4) == "last"){
  305. // Last day of the month at the desired time of day
  306. day = dayMap[day.substr(4,3).toLowerCase()];
  307. d = new Date(getUTCStamp(year, month + 1, 1,
  308. time[1] - 24, time[2], time[3],
  309. off));
  310. dtDay = _d.date.add(d, "minute", -off).getUTCDay();
  311. // Set it to the final day of the correct weekday that month
  312. incr = (day > dtDay) ? (day - dtDay - 7) : (day - dtDay);
  313. if(incr !== 0){
  314. d = _d.date.add(d, "hour", incr * 24);
  315. }
  316. return d;
  317. }else{
  318. day = dayMap[day.substr(0, 3).toLowerCase()];
  319. if(day != "undefined"){
  320. if(rule[4].substr(3, 2) == '>='){
  321. // The stated date of the month
  322. d = new Date(getUTCStamp(year, month, parseInt(rule[4].substr(5), 10),
  323. time[1], time[2], time[3], off));
  324. dtDay = _d.date.add(d, "minute", -off).getUTCDay();
  325. // Set to the first correct weekday after the stated date
  326. incr = (day < dtDay) ? (day - dtDay + 7) : (day - dtDay);
  327. if(incr !== 0){
  328. d = _d.date.add(d, "hour", incr * 24);
  329. }
  330. return d;
  331. }else if(day.substr(3, 2) == '<='){
  332. // The stated date of the month
  333. d = new Date(getUTCStamp(year, month, parseInt(rule[4].substr(5), 10),
  334. time[1], time[2], time[3], off));
  335. dtDay = _d.date.add(d, "minute", -off).getUTCDay();
  336. // Set to first correct weekday before the stated date
  337. incr = (day > dtDay) ? (day - dtDay - 7) : (day - dtDay);
  338. if(incr !== 0){
  339. d = _d.date.add(d, "hour", incr * 24);
  340. }
  341. return d;
  342. }
  343. }
  344. }
  345. }else{
  346. // Numeric date
  347. d = new Date(getUTCStamp(year, month, parseInt(day, 10),
  348. time[1], time[2], time[3], off));
  349. return d;
  350. }
  351. return null;
  352. }
  353. function _getRulesForYear(/* Zone */ zone, /* int */ year){
  354. var rules = [];
  355. _d.forEach(_rules[zone[1]]||[], function(r){
  356. // Clean up rules as needed
  357. for(var i = 0; i < 2; i++){
  358. switch(r[i]){
  359. case "min":
  360. r[i] = _minYear;
  361. break;
  362. case "max":
  363. r[i] = _maxYear;
  364. break;
  365. case "only":
  366. break;
  367. default:
  368. r[i] = parseInt(r[i], 10);
  369. if(isNaN(r[i])){
  370. throw new Error('Invalid year found on rule');
  371. }
  372. break;
  373. }
  374. }
  375. if(typeof r[6] == "string"){
  376. // Change our offset to be an integer
  377. r[6] = getOffsetInMins(r[6]);
  378. }
  379. // Quick-filter to grab all rules that match my year
  380. if((r[0] <= year && r[1] >= year) || // Matches my y
  381. (r[0] == year && r[1] == "only")){ // Matches my only
  382. rules.push({r: r, d: _getRuleStart(r, year, zone[0])});
  383. }
  384. });
  385. return rules;
  386. }
  387. function _loadZoneRanges(/* String */ tz, /* Object[] */ zoneList) {
  388. // summary:
  389. // Loads the zone ranges for the given timezone
  390. var zr = _loadedRanges[tz] = [];
  391. for(var i = 0; i < zoneList.length; i++){
  392. var z = zoneList[i];
  393. var r = zr[i] = [];
  394. var prevZone = null;
  395. var prevRange = null;
  396. var prevRules = [];
  397. // Set up our zone offset to not be a string anymore
  398. if(typeof z[0] == "string"){
  399. z[0] = getOffsetInMins(z[0]);
  400. }
  401. if(i === 0){
  402. // The beginning of zoneinfo time - let's not worry about
  403. // to-the-hour accuracy before Jan 1, 1835
  404. r[0] = Date.UTC(_minYear,0,1,0,0,0,0);
  405. }else{
  406. r[0] = zr[i - 1][1];
  407. prevZone = zoneList[i - 1];
  408. prevRange = zr[i - 1];
  409. prevRules = prevRange[2];
  410. }
  411. // Load the rules that will be going in to our zone
  412. var startYear = new Date(r[0]).getUTCFullYear();
  413. var endYear = z[3] ? parseInt(z[3], 10) : _maxYear;
  414. var rlz = [];
  415. var j;
  416. for(j = startYear; j <= endYear; j++){
  417. rlz = rlz.concat(_getRulesForYear(z, j));
  418. }
  419. rlz.sort(function(a, b){
  420. return _d.date.compare(a.d, b.d);
  421. });
  422. var rl;
  423. for(j = 0, rl; (rl = rlz[j]); j++){
  424. var prevRule = j > 0 ? rlz[j - 1] : null;
  425. if(rl.r[5].indexOf("u") < 0 && rl.r[5].indexOf("s") < 0){
  426. if(j === 0 && i > 0){
  427. if(prevRules.length){
  428. // We have a previous rule - so use it
  429. rl.d = _d.date.add(rl.d, "minute", prevRules[prevRules.length - 1].r[6]);
  430. }else if(_d.date.compare(new Date(prevRange[1]), rl.d, "date") === 0){
  431. // No previous rules - but our date is the same as the
  432. // previous zone ended on - so use that.
  433. rl.d = new Date(prevRange[1]);
  434. }else{
  435. rl.d = _d.date.add(rl.d, "minute", getOffsetInMins(prevZone[1]));
  436. }
  437. }else if(j > 0){
  438. rl.d = _d.date.add(rl.d, "minute", prevRule.r[6]);
  439. }
  440. }
  441. }
  442. r[2] = rlz;
  443. if(!z[3]){
  444. // The end of zoneinfo time - we'll cross this bridge when we
  445. // get close to Dec 31, 2038
  446. r[1] = Date.UTC(_maxYear,11,31,23,59,59,999);
  447. }else{
  448. var year = parseInt(z[3], 10),
  449. month = getMonthNumber(z[4]||"Jan"),
  450. day = parseInt(z[5]||"1", 10),
  451. time = parseTimeString(z[6]||"0");
  452. var utcStmp = r[1] = getUTCStamp(year, month, day,
  453. time[1], time[2], time[3],
  454. ((time[4] == "u") ? 0 : z[0]));
  455. if(isNaN(utcStmp)){
  456. utcStmp = r[1] = _getRuleStart([0,0,0,z[4],z[5],z[6]||"0"],
  457. year, ((time[4] == "u") ? 0 : z[0])).getTime();
  458. }
  459. var matches = _d.filter(rlz, function(rl, idx){
  460. var o = idx > 0 ? rlz[idx - 1].r[6] * 60 * 1000 : 0;
  461. return (rl.d.getTime() < utcStmp + o);
  462. });
  463. if(time[4] != "u" && time[4] != "s"){
  464. if(matches.length){
  465. r[1] += matches[matches.length - 1].r[6] * 60 * 1000;
  466. }else{
  467. r[1] += getOffsetInMins(z[1]) * 60 * 1000;
  468. }
  469. }
  470. }
  471. }
  472. }
  473. function getZoneInfo(/* String */ dt, /* String */ tz) {
  474. // summary:
  475. // Returns the zone entry from the zoneinfo database for the given date
  476. // and timezone
  477. var t = tz;
  478. var zoneList = _zones[t];
  479. // Follow links to get to an actual zone
  480. while(typeof zoneList == "string"){
  481. t = zoneList;
  482. zoneList = _zones[t];
  483. }
  484. if(!zoneList){
  485. // Backward-compat file hasn't loaded yet, try looking in there
  486. if(!_loadedZones.backward){
  487. // This is for backward entries like "America/Fort_Wayne" that
  488. // getRegionForTimezone *thinks* it has a region file and zone
  489. // for (e.g., America => 'northamerica'), but in reality it's a
  490. // legacy zone we need the backward file for
  491. var parsed = loadZoneFile("backward", true);
  492. return getZoneInfo(dt, tz); //Object
  493. }
  494. invalidTZError(t);
  495. }
  496. if(!_loadedRanges[tz]){
  497. _loadZoneRanges(tz, zoneList);
  498. }
  499. var ranges = _loadedRanges[tz];
  500. var tm = dt.getTime();
  501. for(var i = 0, r; (r = ranges[i]); i++){
  502. if(tm >= r[0] && tm < r[1]){
  503. return {zone: zoneList[i], range: ranges[i], idx: i};
  504. }
  505. }
  506. throw new Error('No Zone found for "' + tz + '" on ' + dt);
  507. }
  508. function getRule(/* Date */ dt, /* ZoneInfo */ zoneInfo) {
  509. // summary:
  510. // Returns the latest-matching rule entry from the zoneinfo
  511. // database for the given date and zone
  512. var lastMatch = -1;
  513. var rules = zoneInfo.range[2]||[];
  514. var tsp = dt.getTime();
  515. var zr = zoneInfo.range;
  516. for(var i = 0, r; (r = rules[i]); i++){
  517. if(tsp >= r.d.getTime()){
  518. lastMatch = i;
  519. }
  520. }
  521. if(lastMatch >= 0){
  522. return rules[lastMatch].r;
  523. }
  524. return null;
  525. }
  526. function getAbbreviation(/* String */ tz, /* Object */ zoneInfo, /* Object */ rule) {
  527. // summary:
  528. // Returns the abbreviation for the given zone and rule
  529. var res;
  530. var zone = zoneInfo.zone;
  531. var base = zone[2];
  532. if(base.indexOf('%s') > -1){
  533. var repl;
  534. if(rule){
  535. repl = rule[7];
  536. if(repl == "-"){ repl = ""; }
  537. }else if(zone[1] in abbrExceptions){
  538. repl = abbrExceptions[zone[1]];
  539. }else{
  540. if(zoneInfo.idx > 0){
  541. // Check if our previous zone's base is the same as our
  542. // current in "S" (standard) mode. If so, then use "S"
  543. // for our replacement
  544. var pz = _zones[tz][zoneInfo.idx - 1];
  545. var pb = pz[2];
  546. if(pb.indexOf('%s') < 0){
  547. if(base.replace('%s', "S") == pb){
  548. repl = "S";
  549. }else{
  550. repl = "";
  551. }
  552. }else{
  553. repl = "";
  554. }
  555. }else{
  556. repl = "";
  557. }
  558. }
  559. res = base.replace('%s', repl);
  560. }else if(base.indexOf("/") > -1){
  561. var bs = base.split("/");
  562. if(rule){
  563. res = bs[rule[6] === 0 ? 0 : 1];
  564. }else{
  565. res = bs[0];
  566. }
  567. }else{
  568. res = base;
  569. }
  570. return res; // String
  571. }
  572. /*=====
  573. dojox.date.timezone = function(){
  574. // summary:
  575. // mix-in to dojo.date to provide timezones based on
  576. // the Olson timezone data
  577. //
  578. // description:
  579. // mix-in to dojo.date to provide timezones based on
  580. // the Olson timezone data.
  581. // If you pass "timezone" as a parameter to your format options,
  582. // then you get the date formatted (and offset) for that timezone
  583. //TODOC
  584. };
  585. dojox.date.timezone.getTzInfo = function(dt, tz){
  586. // summary:
  587. // Returns the timezone information for the given date and
  588. // timezone string
  589. //
  590. // dt: Date
  591. // The Date - a "proxyDate"
  592. //
  593. // tz: String
  594. // String representation of the timezone you want to get info
  595. // for date
  596. };
  597. dojox.date.timezone.loadZoneData = function(data){
  598. // summary:
  599. // Loads the given data object into the zone database
  600. //
  601. // data: Object
  602. // The data to load - contains "zones" and "rules" parameters
  603. };
  604. dojox.date.timezone.getAllZones = function(){
  605. // summary:
  606. // Returns an array of zones that have been loaded
  607. };
  608. =====*/
  609. _d.setObject("dojox.date.timezone", {
  610. getTzInfo: function(/* Date */ dt, /* String */ tz){
  611. // Lazy-load any zones not yet loaded
  612. if(loadingScheme == "lazyLoad"){
  613. // Get the correct region for the zone
  614. var zoneFile = getRegionForTimezone(tz);
  615. if(!zoneFile){
  616. throw new Error("Not a valid timezone ID.");
  617. }else{
  618. if(!_loadedZones[zoneFile]){
  619. // Get the file and parse it -- use synchronous XHR
  620. loadZoneFile(zoneFile);
  621. }
  622. }
  623. }
  624. var zoneInfo = getZoneInfo(dt, tz);
  625. var off = zoneInfo.zone[0];
  626. // See if the offset needs adjustment
  627. var rule = getRule(dt, zoneInfo);
  628. if(rule){
  629. off += rule[6];
  630. }else{
  631. if(_rules[zoneInfo.zone[1]] && zoneInfo.idx > 0){
  632. off += getOffsetInMins(_zones[tz][zoneInfo.idx - 1][1]);
  633. }else{
  634. off += getOffsetInMins(zoneInfo.zone[1]);
  635. }
  636. }
  637. var abbr = getAbbreviation(tz, zoneInfo, rule);
  638. return { tzOffset: off, tzAbbr: abbr }; // Object
  639. },
  640. loadZoneData: function(data){
  641. loadZoneData(data);
  642. },
  643. getAllZones: function(){
  644. var arr = [];
  645. for(var z in _zones){ arr.push(z); }
  646. arr.sort();
  647. return arr; // String[]
  648. }
  649. });
  650. // Now - initialize the stuff that we should have pre-loaded
  651. if(typeof defaultZoneFile == "string" && defaultZoneFile){
  652. defaultZoneFile = [defaultZoneFile];
  653. }
  654. if(_d.isArray(defaultZoneFile)){
  655. _d.forEach(defaultZoneFile, function(f){
  656. loadZoneFile(f);
  657. });
  658. }
  659. // And enhance the default formatting functions
  660. // If you pass "timezone" as a parameter to your format options,
  661. // then you get the date formatted (and offset) for that timezone
  662. var oLocaleFmt = _d.date.locale.format,
  663. oGetZone = _d.date.locale._getZone;
  664. _d.date.locale.format = function(dateObject, options){
  665. options = options||{};
  666. if(options.timezone && !options._tzInfo){
  667. // Store it in our options so we can use it later
  668. options._tzInfo = dojox.date.timezone.getTzInfo(dateObject, options.timezone);
  669. }
  670. if(options._tzInfo){
  671. // Roll our date to display the correct time according to the
  672. // desired offset
  673. var offset = dateObject.getTimezoneOffset() - options._tzInfo.tzOffset;
  674. dateObject = new Date(dateObject.getTime() + (offset * 60 * 1000));
  675. }
  676. return oLocaleFmt.call(this, dateObject, options);
  677. };
  678. _d.date.locale._getZone = function(dateObject, getName, options){
  679. if(options._tzInfo){
  680. return getName ? options._tzInfo.tzAbbr : options._tzInfo.tzOffset;
  681. }
  682. return oGetZone.call(this, dateObject, getName, options);
  683. };
  684. })(dojo);
  685. }