locale.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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.islamic.locale"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.date.islamic.locale"] = true;
  8. dojo.provide("dojox.date.islamic.locale");
  9. dojo.require("dojox.date.islamic.Date");
  10. dojo.require("dojo.regexp");
  11. dojo.require("dojo.string");
  12. dojo.require("dojo.i18n");
  13. dojo.require("dojo.date");
  14. dojo.requireLocalization("dojo.cldr", "islamic", null, "ROOT,ar,bg,bn,bs,da,de,en,en-gb,es,fa,fi,fr,he,hi,hu,id,in,it,iw,lv,ml,ms,nb,nl,no,pl,pt,pt-pt,ru,sr,sv,th,tr,uk,ur,vi,zh,zh-hant");
  15. (function(){
  16. // Format a pattern without literals
  17. function formatPattern(dateObject, bundle, locale, fullYear, pattern){
  18. return pattern.replace(/([a-z])\1*/ig, function(match){
  19. var s, pad;
  20. var c = match.charAt(0);
  21. var l = match.length;
  22. var widthList = ["abbr", "wide", "narrow"];
  23. switch(c){
  24. case 'G':
  25. s = bundle["eraAbbr"][0];
  26. break;
  27. case 'y':
  28. s = String(dateObject.getFullYear());
  29. break;
  30. case 'M':
  31. var m = dateObject.getMonth();
  32. if(l<3){
  33. s = m+1; pad = true;
  34. }else{
  35. var propM = ["months", "format", widthList[l-3]].join("-");
  36. s = bundle[propM][m];
  37. }
  38. break;
  39. case 'd':
  40. s = dateObject.getDate(true); pad = true;
  41. break;
  42. case 'E':
  43. var d = dateObject.getDay();
  44. if(l<3){
  45. s = d+1; pad = true;
  46. }else{
  47. var propD = ["days", "format", widthList[l-3]].join("-");
  48. s = bundle[propD][d];
  49. }
  50. break;
  51. case 'a':
  52. var timePeriod = (dateObject.getHours() < 12) ? 'am' : 'pm';
  53. s = bundle['dayPeriods-format-wide-' + timePeriod];
  54. break;
  55. case 'h':
  56. case 'H':
  57. case 'K':
  58. case 'k':
  59. var h = dateObject.getHours();
  60. switch (c){
  61. case 'h': // 1-12
  62. s = (h % 12) || 12;
  63. break;
  64. case 'H': // 0-23
  65. s = h;
  66. break;
  67. case 'K': // 0-11
  68. s = (h % 12);
  69. break;
  70. case 'k': // 1-24
  71. s = h || 24;
  72. break;
  73. }
  74. pad = true;
  75. break;
  76. case 'm':
  77. s = dateObject.getMinutes(); pad = true;
  78. break;
  79. case 's':
  80. s = dateObject.getSeconds(); pad = true;
  81. break;
  82. case 'S':
  83. s = Math.round(dateObject.getMilliseconds() * Math.pow(10, l-3)); pad = true;
  84. break;
  85. case 'z':
  86. // We only have one timezone to offer; the one from the browser
  87. s = dojo.date.getTimezoneName(dateObject.toGregorian());
  88. if(s){ break; }
  89. l = 4;
  90. // fallthrough... use GMT if tz not available
  91. case 'Z':
  92. var offset = dateObject.toGregorian().getTimezoneOffset();
  93. var tz = [
  94. (offset <= 0 ? "+" : "-"),
  95. dojo.string.pad(Math.floor(Math.abs(offset) / 60), 2),
  96. dojo.string.pad(Math.abs(offset) % 60, 2)
  97. ];
  98. if(l == 4){
  99. tz.splice(0, 0, "GMT");
  100. tz.splice(3, 0, ":");
  101. }
  102. s = tz.join("");
  103. break;
  104. default:
  105. throw new Error("dojox.date.islamic.locale.formatPattern: invalid pattern char: "+pattern);
  106. }
  107. if(pad){ s = dojo.string.pad(s, l); }
  108. return s;
  109. });
  110. }
  111. // based on and similar to dojo.date.locale.format
  112. dojox.date.islamic.locale.format = function(/*islamic.Date*/dateObject, /*Object?*/options){
  113. // summary:
  114. // Format a Date object as a String, using settings.
  115. options = options || {};
  116. var locale = dojo.i18n.normalizeLocale(options.locale);
  117. var formatLength = options.formatLength || 'short';
  118. var bundle = dojox.date.islamic.locale._getIslamicBundle(locale);
  119. var str = [];
  120. var sauce = dojo.hitch(this, formatPattern, dateObject, bundle, locale, options.fullYear);
  121. if(options.selector == "year"){
  122. var year = dateObject.getFullYear();
  123. return year;
  124. }
  125. if(options.selector != "time"){
  126. var datePattern = options.datePattern || bundle["dateFormat-"+formatLength];
  127. if(datePattern){str.push(_processPattern(datePattern, sauce));}
  128. }
  129. if(options.selector != "date"){
  130. var timePattern = options.timePattern || bundle["timeFormat-"+formatLength];
  131. if(timePattern){str.push(_processPattern(timePattern, sauce));}
  132. }
  133. var result = str.join(" "); //TODO: use locale-specific pattern to assemble date + time
  134. return result; // String
  135. };
  136. dojox.date.islamic.locale.regexp = function(/*object?*/options){
  137. // based on and similar to dojo.date.locale.regexp
  138. // summary:
  139. // Builds the regular needed to parse a islamic.Date
  140. return dojox.date.islamic.locale._parseInfo(options).regexp; // String
  141. };
  142. dojox.date.islamic.locale._parseInfo = function(/*oblect?*/options){
  143. /* based on and similar to dojo.date.locale._parseInfo */
  144. options = options || {};
  145. var locale = dojo.i18n.normalizeLocale(options.locale);
  146. var bundle = dojox.date.islamic.locale._getIslamicBundle(locale);
  147. var formatLength = options.formatLength || 'short';
  148. var datePattern = options.datePattern || bundle["dateFormat-" + formatLength];
  149. var timePattern = options.timePattern || bundle["timeFormat-" + formatLength];
  150. var pattern;
  151. if(options.selector == 'date'){
  152. pattern = datePattern;
  153. }else if(options.selector == 'time'){
  154. pattern = timePattern;
  155. }else{
  156. pattern = (typeof (timePattern) == "undefined") ? datePattern : datePattern + ' ' + timePattern;
  157. }
  158. var tokens = [];
  159. var re = _processPattern(pattern, dojo.hitch(this, _buildDateTimeRE, tokens, bundle, options));
  160. return {regexp: re, tokens: tokens, bundle: bundle};
  161. };
  162. dojox.date.islamic.locale.parse= function(/*String*/value, /*Object?*/options){
  163. // based on and similar to dojo.date.locale.parse
  164. // summary: This function parse string date value according to options
  165. value = value.replace(/[\u200E\u200F\u202A\u202E]/g, ""); //remove bidi non-printing chars
  166. if(!options){ options={}; }
  167. var info = dojox.date.islamic.locale._parseInfo(options);
  168. var tokens = info.tokens, bundle = info.bundle;
  169. var regexp = info.regexp.replace(/[\u200E\u200F\u202A\u202E]/g, ""); //remove bidi non-printing chars from the pattern
  170. var re = new RegExp("^" + regexp + "$");
  171. var match = re.exec(value);
  172. var locale = dojo.i18n.normalizeLocale(options.locale);
  173. if(!match){ return null; } // null
  174. var date, date1;
  175. var result = [1389,0,1,0,0,0,0]; //FIXME: islamic date for [1970,0,1,0,0,0,0] used in gregorian locale
  176. var amPm = "";
  177. var mLength = 0;
  178. var widthList = ["abbr", "wide", "narrow"];
  179. var valid = dojo.every(match, function(v, i){
  180. if(!i){return true;}
  181. var token=tokens[i-1];
  182. var l=token.length;
  183. switch(token.charAt(0)){
  184. case 'y':
  185. result[0] = Number(v);
  186. break;
  187. case 'M':
  188. if(l>2){
  189. var months = bundle['months-format-' + widthList[l-3]].concat();
  190. if(!options.strict){
  191. //Tolerate abbreviating period in month part
  192. //Case-insensitive comparison
  193. v = v.replace(".","").toLowerCase();
  194. months = dojo.map(months, function(s){ return s ? s.replace(".","").toLowerCase() : s; } );
  195. }
  196. v = dojo.indexOf(months, v);
  197. if(v == -1){
  198. return false;
  199. }
  200. mLength = l;
  201. }else{
  202. v--;
  203. }
  204. result[1] = Number(v);
  205. break;
  206. case 'D':
  207. result[1] = 0;
  208. // fallthrough...
  209. case 'd':
  210. result[2] = Number(v);
  211. break;
  212. case 'a': //am/pm
  213. var am = options.am || bundle['dayPeriods-format-wide-am'],
  214. pm = options.pm || bundle['dayPeriods-format-wide-pm'];
  215. if(!options.strict){
  216. var period = /\./g;
  217. v = v.replace(period,'').toLowerCase();
  218. am = am.replace(period,'').toLowerCase();
  219. pm = pm.replace(period,'').toLowerCase();
  220. }
  221. if(options.strict && v != am && v != pm){
  222. return false;
  223. }
  224. // we might not have seen the hours field yet, so store the state and apply hour change later
  225. amPm = (v == pm) ? 'p' : (v == am) ? 'a' : '';
  226. break;
  227. case 'K': //hour (1-24)
  228. if(v == 24){ v = 0; }
  229. // fallthrough...
  230. case 'h': //hour (1-12)
  231. case 'H': //hour (0-23)
  232. case 'k': //hour (0-11)
  233. //in the 12-hour case, adjusting for am/pm requires the 'a' part
  234. //which could come before or after the hour, so we will adjust later
  235. result[3] = Number(v);
  236. break;
  237. case 'm': //minutes
  238. result[4] = Number(v);
  239. break;
  240. case 's': //seconds
  241. result[5] = Number(v);
  242. break;
  243. case 'S': //milliseconds
  244. result[6] = Number(v);
  245. }
  246. return true;
  247. });
  248. var hours = +result[3];
  249. if(amPm === 'p' && hours < 12){
  250. result[3] = hours + 12; //e.g., 3pm -> 15
  251. }else if(amPm === 'a' && hours == 12){
  252. result[3] = 0; //12am -> 0
  253. }
  254. var dateObject = new dojox.date.islamic.Date(result[0], result[1], result[2], result[3], result[4], result[5], result[6]);
  255. return dateObject;
  256. };
  257. function _processPattern(pattern, applyPattern, applyLiteral, applyAll){
  258. //summary: Process a pattern with literals in it
  259. // Break up on single quotes, treat every other one as a literal, except '' which becomes '
  260. var identity = function(x){return x;};
  261. applyPattern = applyPattern || identity;
  262. applyLiteral = applyLiteral || identity;
  263. applyAll = applyAll || identity;
  264. //split on single quotes (which escape literals in date format strings)
  265. //but preserve escaped single quotes (e.g., o''clock)
  266. var chunks = pattern.match(/(''|[^'])+/g);
  267. var literal = pattern.charAt(0) == "'";
  268. dojo.forEach(chunks, function(chunk, i){
  269. if(!chunk){
  270. chunks[i]='';
  271. }else{
  272. chunks[i]=(literal ? applyLiteral : applyPattern)(chunk);
  273. literal = !literal;
  274. }
  275. });
  276. return applyAll(chunks.join(''));
  277. }
  278. function _buildDateTimeRE (tokens, bundle, options, pattern){
  279. // based on and similar to dojo.date.locale._buildDateTimeRE
  280. //
  281. pattern = dojo.regexp.escapeString(pattern);
  282. var locale = dojo.i18n.normalizeLocale(options.locale);
  283. return pattern.replace(/([a-z])\1*/ig, function(match){
  284. // Build a simple regexp. Avoid captures, which would ruin the tokens list
  285. var s;
  286. var c = match.charAt(0);
  287. var l = match.length;
  288. var p2 = '', p3 = '';
  289. if(options.strict){
  290. if(l > 1){ p2 = '0' + '{'+(l-1)+'}'; }
  291. if(l > 2){ p3 = '0' + '{'+(l-2)+'}'; }
  292. }else{
  293. p2 = '0?'; p3 = '0{0,2}';
  294. }
  295. switch(c){
  296. case 'y':
  297. s = '\\d+';
  298. break;
  299. case 'M':
  300. s = (l>2) ? '\\S+ ?\\S+' : p2+'[1-9]|1[0-2]';
  301. break;
  302. case 'd':
  303. s = '[12]\\d|'+p2+'[1-9]|3[01]';
  304. break;
  305. case 'E':
  306. s = '\\S+';
  307. break;
  308. case 'h': //hour (1-12)
  309. s = p2+'[1-9]|1[0-2]';
  310. break;
  311. case 'k': //hour (0-11)
  312. s = p2+'\\d|1[01]';
  313. break;
  314. case 'H': //hour (0-23)
  315. s = p2+'\\d|1\\d|2[0-3]';
  316. break;
  317. case 'K': //hour (1-24)
  318. s = p2+'[1-9]|1\\d|2[0-4]';
  319. break;
  320. case 'm':
  321. case 's':
  322. s = p2+'\\d|[0-5]\\d';
  323. break;
  324. case 'S':
  325. s = '\\d{'+l+'}';
  326. break;
  327. case 'a':
  328. var am = options.am || bundle['dayPeriods-format-wide-am'],
  329. pm = options.pm || bundle['dayPeriods-format-wide-pm'];
  330. if(options.strict){
  331. s = am + '|' + pm;
  332. }else{
  333. s = am + '|' + pm;
  334. if(am != am.toLowerCase()){ s += '|' + am.toLowerCase(); }
  335. if(pm != pm.toLowerCase()){ s += '|' + pm.toLowerCase(); }
  336. }
  337. break;
  338. default:
  339. s = ".*";
  340. }
  341. if(tokens){ tokens.push(match); }
  342. return "(" + s + ")"; // add capture
  343. }).replace(/[\xa0 ]/g, "[\\s\\xa0]"); // normalize whitespace. Need explicit handling of \xa0 for IE. */
  344. }
  345. })();
  346. (function(){
  347. var _customFormats = [];
  348. dojox.date.islamic.locale.addCustomFormats = function(/*String*/packageName, /*String*/bundleName){
  349. // summary:
  350. // Add a reference to a bundle containing localized custom formats to be
  351. // used by date/time formatting and parsing routines.
  352. _customFormats.push({pkg:packageName,name:bundleName});
  353. };
  354. dojox.date.islamic.locale._getIslamicBundle = function(/*String*/locale){
  355. var islamic = {};
  356. dojo.forEach(_customFormats, function(desc){
  357. var bundle = dojo.i18n.getLocalization(desc.pkg, desc.name, locale);
  358. islamic = dojo.mixin(islamic, bundle);
  359. }, this);
  360. return islamic; /*Object*/
  361. };
  362. })();
  363. dojox.date.islamic.locale.addCustomFormats("dojo.cldr","islamic");
  364. dojox.date.islamic.locale.getNames = function(/*String*/item, /*String*/type, /*String?*/context, /*String?*/locale, /*islamic Date Object?*/date){
  365. // summary:
  366. // Used to get localized strings from dojo.cldr for day or month names.
  367. var label;
  368. var lookup = dojox.date.islamic.locale._getIslamicBundle(locale);
  369. var props = [item, context, type];
  370. if(context == 'standAlone'){
  371. var key = props.join('-');
  372. label = lookup[key];
  373. // Fall back to 'format' flavor of name
  374. if(label[0] == 1){ label = undefined; } // kludge, in the absence of real aliasing support in dojo.cldr
  375. }
  376. props[1] = 'format';
  377. // return by copy so changes won't be made accidentally to the in-memory model
  378. return (label || lookup[props.join('-')]).concat(); /*Array*/
  379. };
  380. dojox.date.islamic.locale.weekDays = dojox.date.islamic.locale.getNames('days', 'wide', 'format');
  381. dojox.date.islamic.locale.months = dojox.date.islamic.locale.getNames('months', 'wide', 'format');
  382. }