locale.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. define("dojo/date/locale", [
  2. "../_base/kernel",
  3. "../_base/lang",
  4. "../_base/array",
  5. "../date",
  6. "../cldr/supplemental",
  7. "../regexp",
  8. "../string",
  9. "../i18n!../cldr/nls/gregorian"
  10. ], function(dojo, lang, array, date, cldr, regexp, string, gregorian) {
  11. // module:
  12. // dojo/date/locale
  13. // summary:
  14. // This modules defines dojo.date.locale, localization methods for Date.
  15. lang.getObject("date.locale", true, dojo);
  16. // Localization methods for Date. Honor local customs using locale-dependent dojo.cldr data.
  17. // Load the bundles containing localization information for
  18. // names and formats
  19. //NOTE: Everything in this module assumes Gregorian calendars.
  20. // Other calendars will be implemented in separate modules.
  21. // Format a pattern without literals
  22. function formatPattern(dateObject, bundle, options, pattern){
  23. return pattern.replace(/([a-z])\1*/ig, function(match){
  24. var s, pad,
  25. c = match.charAt(0),
  26. l = match.length,
  27. widthList = ["abbr", "wide", "narrow"];
  28. switch(c){
  29. case 'G':
  30. s = bundle[(l < 4) ? "eraAbbr" : "eraNames"][dateObject.getFullYear() < 0 ? 0 : 1];
  31. break;
  32. case 'y':
  33. s = dateObject.getFullYear();
  34. switch(l){
  35. case 1:
  36. break;
  37. case 2:
  38. if(!options.fullYear){
  39. s = String(s); s = s.substr(s.length - 2);
  40. break;
  41. }
  42. // fallthrough
  43. default:
  44. pad = true;
  45. }
  46. break;
  47. case 'Q':
  48. case 'q':
  49. s = Math.ceil((dateObject.getMonth()+1)/3);
  50. // switch(l){
  51. // case 1: case 2:
  52. pad = true;
  53. // break;
  54. // case 3: case 4: // unimplemented
  55. // }
  56. break;
  57. case 'M':
  58. var m = dateObject.getMonth();
  59. if(l<3){
  60. s = m+1; pad = true;
  61. }else{
  62. var propM = ["months", "format", widthList[l-3]].join("-");
  63. s = bundle[propM][m];
  64. }
  65. break;
  66. case 'w':
  67. var firstDay = 0;
  68. s = dojo.date.locale._getWeekOfYear(dateObject, firstDay); pad = true;
  69. break;
  70. case 'd':
  71. s = dateObject.getDate(); pad = true;
  72. break;
  73. case 'D':
  74. s = dojo.date.locale._getDayOfYear(dateObject); pad = true;
  75. break;
  76. case 'E':
  77. var d = dateObject.getDay();
  78. if(l<3){
  79. s = d+1; pad = true;
  80. }else{
  81. var propD = ["days", "format", widthList[l-3]].join("-");
  82. s = bundle[propD][d];
  83. }
  84. break;
  85. case 'a':
  86. var timePeriod = (dateObject.getHours() < 12) ? 'am' : 'pm';
  87. s = options[timePeriod] || bundle['dayPeriods-format-wide-' + timePeriod];
  88. break;
  89. case 'h':
  90. case 'H':
  91. case 'K':
  92. case 'k':
  93. var h = dateObject.getHours();
  94. // strange choices in the date format make it impossible to write this succinctly
  95. switch (c){
  96. case 'h': // 1-12
  97. s = (h % 12) || 12;
  98. break;
  99. case 'H': // 0-23
  100. s = h;
  101. break;
  102. case 'K': // 0-11
  103. s = (h % 12);
  104. break;
  105. case 'k': // 1-24
  106. s = h || 24;
  107. break;
  108. }
  109. pad = true;
  110. break;
  111. case 'm':
  112. s = dateObject.getMinutes(); pad = true;
  113. break;
  114. case 's':
  115. s = dateObject.getSeconds(); pad = true;
  116. break;
  117. case 'S':
  118. s = Math.round(dateObject.getMilliseconds() * Math.pow(10, l-3)); pad = true;
  119. break;
  120. case 'v': // FIXME: don't know what this is. seems to be same as z?
  121. case 'z':
  122. // We only have one timezone to offer; the one from the browser
  123. s = dojo.date.locale._getZone(dateObject, true, options);
  124. if(s){break;}
  125. l=4;
  126. // fallthrough... use GMT if tz not available
  127. case 'Z':
  128. var offset = dojo.date.locale._getZone(dateObject, false, options);
  129. var tz = [
  130. (offset<=0 ? "+" : "-"),
  131. string.pad(Math.floor(Math.abs(offset)/60), 2),
  132. string.pad(Math.abs(offset)% 60, 2)
  133. ];
  134. if(l==4){
  135. tz.splice(0, 0, "GMT");
  136. tz.splice(3, 0, ":");
  137. }
  138. s = tz.join("");
  139. break;
  140. // case 'Y': case 'u': case 'W': case 'F': case 'g': case 'A': case 'e':
  141. // console.log(match+" modifier unimplemented");
  142. default:
  143. throw new Error("dojo.date.locale.format: invalid pattern char: "+pattern);
  144. }
  145. if(pad){ s = string.pad(s, l); }
  146. return s;
  147. });
  148. }
  149. /*=====
  150. dojo.date.locale.__FormatOptions = function(){
  151. // selector: String
  152. // choice of 'time','date' (default: date and time)
  153. // formatLength: String
  154. // choice of long, short, medium or full (plus any custom additions). Defaults to 'short'
  155. // datePattern:String
  156. // override pattern with this string
  157. // timePattern:String
  158. // override pattern with this string
  159. // am: String
  160. // override strings for am in times
  161. // pm: String
  162. // override strings for pm in times
  163. // locale: String
  164. // override the locale used to determine formatting rules
  165. // fullYear: Boolean
  166. // (format only) use 4 digit years whenever 2 digit years are called for
  167. // strict: Boolean
  168. // (parse only) strict parsing, off by default
  169. this.selector = selector;
  170. this.formatLength = formatLength;
  171. this.datePattern = datePattern;
  172. this.timePattern = timePattern;
  173. this.am = am;
  174. this.pm = pm;
  175. this.locale = locale;
  176. this.fullYear = fullYear;
  177. this.strict = strict;
  178. }
  179. =====*/
  180. dojo.date.locale._getZone = function(/*Date*/dateObject, /*boolean*/getName, /*dojo.date.locale.__FormatOptions?*/options){
  181. // summary:
  182. // Returns the zone (or offset) for the given date and options. This
  183. // is broken out into a separate function so that it can be overridden
  184. // by timezone-aware code.
  185. //
  186. // dateObject:
  187. // the date and/or time being formatted.
  188. //
  189. // getName:
  190. // Whether to return the timezone string (if true), or the offset (if false)
  191. //
  192. // options:
  193. // The options being used for formatting
  194. if(getName){
  195. return date.getTimezoneName(dateObject);
  196. }else{
  197. return dateObject.getTimezoneOffset();
  198. }
  199. };
  200. dojo.date.locale.format = function(/*Date*/dateObject, /*dojo.date.locale.__FormatOptions?*/options){
  201. // summary:
  202. // Format a Date object as a String, using locale-specific settings.
  203. //
  204. // description:
  205. // Create a string from a Date object using a known localized pattern.
  206. // By default, this method formats both date and time from dateObject.
  207. // Formatting patterns are chosen appropriate to the locale. Different
  208. // formatting lengths may be chosen, with "full" used by default.
  209. // Custom patterns may be used or registered with translations using
  210. // the dojo.date.locale.addCustomFormats method.
  211. // Formatting patterns are implemented using [the syntax described at
  212. // unicode.org](http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns)
  213. //
  214. // dateObject:
  215. // the date and/or time to be formatted. If a time only is formatted,
  216. // the values in the year, month, and day fields are irrelevant. The
  217. // opposite is true when formatting only dates.
  218. options = options || {};
  219. var locale = dojo.i18n.normalizeLocale(options.locale),
  220. formatLength = options.formatLength || 'short',
  221. bundle = dojo.date.locale._getGregorianBundle(locale),
  222. str = [],
  223. sauce = lang.hitch(this, formatPattern, dateObject, bundle, options);
  224. if(options.selector == "year"){
  225. return _processPattern(bundle["dateFormatItem-yyyy"] || "yyyy", sauce);
  226. }
  227. var pattern;
  228. if(options.selector != "date"){
  229. pattern = options.timePattern || bundle["timeFormat-"+formatLength];
  230. if(pattern){str.push(_processPattern(pattern, sauce));}
  231. }
  232. if(options.selector != "time"){
  233. pattern = options.datePattern || bundle["dateFormat-"+formatLength];
  234. if(pattern){str.push(_processPattern(pattern, sauce));}
  235. }
  236. return str.length == 1 ? str[0] : bundle["dateTimeFormat-"+formatLength].replace(/\{(\d+)\}/g,
  237. function(match, key){ return str[key]; }); // String
  238. };
  239. dojo.date.locale.regexp = function(/*dojo.date.locale.__FormatOptions?*/options){
  240. // summary:
  241. // Builds the regular needed to parse a localized date
  242. return dojo.date.locale._parseInfo(options).regexp; // String
  243. };
  244. dojo.date.locale._parseInfo = function(/*dojo.date.locale.__FormatOptions?*/options){
  245. options = options || {};
  246. var locale = dojo.i18n.normalizeLocale(options.locale),
  247. bundle = dojo.date.locale._getGregorianBundle(locale),
  248. formatLength = options.formatLength || 'short',
  249. datePattern = options.datePattern || bundle["dateFormat-" + formatLength],
  250. timePattern = options.timePattern || bundle["timeFormat-" + formatLength],
  251. pattern;
  252. if(options.selector == 'date'){
  253. pattern = datePattern;
  254. }else if(options.selector == 'time'){
  255. pattern = timePattern;
  256. }else{
  257. pattern = bundle["dateTimeFormat-"+formatLength].replace(/\{(\d+)\}/g,
  258. function(match, key){ return [timePattern, datePattern][key]; });
  259. }
  260. var tokens = [],
  261. re = _processPattern(pattern, lang.hitch(this, _buildDateTimeRE, tokens, bundle, options));
  262. return {regexp: re, tokens: tokens, bundle: bundle};
  263. };
  264. dojo.date.locale.parse = function(/*String*/value, /*dojo.date.locale.__FormatOptions?*/options){
  265. // summary:
  266. // Convert a properly formatted string to a primitive Date object,
  267. // using locale-specific settings.
  268. //
  269. // description:
  270. // Create a Date object from a string using a known localized pattern.
  271. // By default, this method parses looking for both date and time in the string.
  272. // Formatting patterns are chosen appropriate to the locale. Different
  273. // formatting lengths may be chosen, with "full" used by default.
  274. // Custom patterns may be used or registered with translations using
  275. // the dojo.date.locale.addCustomFormats method.
  276. //
  277. // Formatting patterns are implemented using [the syntax described at
  278. // unicode.org](http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns)
  279. // When two digit years are used, a century is chosen according to a sliding
  280. // window of 80 years before and 20 years after present year, for both `yy` and `yyyy` patterns.
  281. // year < 100CE requires strict mode.
  282. //
  283. // value:
  284. // A string representation of a date
  285. // remove non-printing bidi control chars from input and pattern
  286. var controlChars = /[\u200E\u200F\u202A\u202E]/g,
  287. info = dojo.date.locale._parseInfo(options),
  288. tokens = info.tokens, bundle = info.bundle,
  289. re = new RegExp("^" + info.regexp.replace(controlChars, "") + "$",
  290. info.strict ? "" : "i"),
  291. match = re.exec(value && value.replace(controlChars, ""));
  292. if(!match){ return null; } // null
  293. var widthList = ['abbr', 'wide', 'narrow'],
  294. result = [1970,0,1,0,0,0,0], // will get converted to a Date at the end
  295. amPm = "",
  296. valid = dojo.every(match, function(v, i){
  297. if(!i){return true;}
  298. var token=tokens[i-1];
  299. var l=token.length;
  300. switch(token.charAt(0)){
  301. case 'y':
  302. if(l != 2 && options.strict){
  303. //interpret year literally, so '5' would be 5 A.D.
  304. result[0] = v;
  305. }else{
  306. if(v<100){
  307. v = Number(v);
  308. //choose century to apply, according to a sliding window
  309. //of 80 years before and 20 years after present year
  310. var year = '' + new Date().getFullYear(),
  311. century = year.substring(0, 2) * 100,
  312. cutoff = Math.min(Number(year.substring(2, 4)) + 20, 99);
  313. result[0] = (v < cutoff) ? century + v : century - 100 + v;
  314. }else{
  315. //we expected 2 digits and got more...
  316. if(options.strict){
  317. return false;
  318. }
  319. //interpret literally, so '150' would be 150 A.D.
  320. //also tolerate '1950', if 'yyyy' input passed to 'yy' format
  321. result[0] = v;
  322. }
  323. }
  324. break;
  325. case 'M':
  326. if(l>2){
  327. var months = bundle['months-format-' + widthList[l-3]].concat();
  328. if(!options.strict){
  329. //Tolerate abbreviating period in month part
  330. //Case-insensitive comparison
  331. v = v.replace(".","").toLowerCase();
  332. months = dojo.map(months, function(s){ return s.replace(".","").toLowerCase(); } );
  333. }
  334. v = dojo.indexOf(months, v);
  335. if(v == -1){
  336. // console.log("dojo.date.locale.parse: Could not parse month name: '" + v + "'.");
  337. return false;
  338. }
  339. }else{
  340. v--;
  341. }
  342. result[1] = v;
  343. break;
  344. case 'E':
  345. case 'e':
  346. var days = bundle['days-format-' + widthList[l-3]].concat();
  347. if(!options.strict){
  348. //Case-insensitive comparison
  349. v = v.toLowerCase();
  350. days = dojo.map(days, function(d){return d.toLowerCase();});
  351. }
  352. v = dojo.indexOf(days, v);
  353. if(v == -1){
  354. // console.log("dojo.date.locale.parse: Could not parse weekday name: '" + v + "'.");
  355. return false;
  356. }
  357. //TODO: not sure what to actually do with this input,
  358. //in terms of setting something on the Date obj...?
  359. //without more context, can't affect the actual date
  360. //TODO: just validate?
  361. break;
  362. case 'D':
  363. result[1] = 0;
  364. // fallthrough...
  365. case 'd':
  366. result[2] = v;
  367. break;
  368. case 'a': //am/pm
  369. var am = options.am || bundle['dayPeriods-format-wide-am'],
  370. pm = options.pm || bundle['dayPeriods-format-wide-pm'];
  371. if(!options.strict){
  372. var period = /\./g;
  373. v = v.replace(period,'').toLowerCase();
  374. am = am.replace(period,'').toLowerCase();
  375. pm = pm.replace(period,'').toLowerCase();
  376. }
  377. if(options.strict && v != am && v != pm){
  378. // console.log("dojo.date.locale.parse: Could not parse am/pm part.");
  379. return false;
  380. }
  381. // we might not have seen the hours field yet, so store the state and apply hour change later
  382. amPm = (v == pm) ? 'p' : (v == am) ? 'a' : '';
  383. break;
  384. case 'K': //hour (1-24)
  385. if(v == 24){ v = 0; }
  386. // fallthrough...
  387. case 'h': //hour (1-12)
  388. case 'H': //hour (0-23)
  389. case 'k': //hour (0-11)
  390. //TODO: strict bounds checking, padding
  391. if(v > 23){
  392. // console.log("dojo.date.locale.parse: Illegal hours value");
  393. return false;
  394. }
  395. //in the 12-hour case, adjusting for am/pm requires the 'a' part
  396. //which could come before or after the hour, so we will adjust later
  397. result[3] = v;
  398. break;
  399. case 'm': //minutes
  400. result[4] = v;
  401. break;
  402. case 's': //seconds
  403. result[5] = v;
  404. break;
  405. case 'S': //milliseconds
  406. result[6] = v;
  407. // break;
  408. // case 'w':
  409. //TODO var firstDay = 0;
  410. // default:
  411. //TODO: throw?
  412. // console.log("dojo.date.locale.parse: unsupported pattern char=" + token.charAt(0));
  413. }
  414. return true;
  415. });
  416. var hours = +result[3];
  417. if(amPm === 'p' && hours < 12){
  418. result[3] = hours + 12; //e.g., 3pm -> 15
  419. }else if(amPm === 'a' && hours == 12){
  420. result[3] = 0; //12am -> 0
  421. }
  422. //TODO: implement a getWeekday() method in order to test
  423. //validity of input strings containing 'EEE' or 'EEEE'...
  424. var dateObject = new Date(result[0], result[1], result[2], result[3], result[4], result[5], result[6]); // Date
  425. if(options.strict){
  426. dateObject.setFullYear(result[0]);
  427. }
  428. // Check for overflow. The Date() constructor normalizes things like April 32nd...
  429. //TODO: why isn't this done for times as well?
  430. var allTokens = tokens.join(""),
  431. dateToken = allTokens.indexOf('d') != -1,
  432. monthToken = allTokens.indexOf('M') != -1;
  433. if(!valid ||
  434. (monthToken && dateObject.getMonth() > result[1]) ||
  435. (dateToken && dateObject.getDate() > result[2])){
  436. return null;
  437. }
  438. // Check for underflow, due to DST shifts. See #9366
  439. // This assumes a 1 hour dst shift correction at midnight
  440. // We could compare the timezone offset after the shift and add the difference instead.
  441. if((monthToken && dateObject.getMonth() < result[1]) ||
  442. (dateToken && dateObject.getDate() < result[2])){
  443. dateObject = date.add(dateObject, "hour", 1);
  444. }
  445. return dateObject; // Date
  446. };
  447. function _processPattern(pattern, applyPattern, applyLiteral, applyAll){
  448. //summary: Process a pattern with literals in it
  449. // Break up on single quotes, treat every other one as a literal, except '' which becomes '
  450. var identity = function(x){return x;};
  451. applyPattern = applyPattern || identity;
  452. applyLiteral = applyLiteral || identity;
  453. applyAll = applyAll || identity;
  454. //split on single quotes (which escape literals in date format strings)
  455. //but preserve escaped single quotes (e.g., o''clock)
  456. var chunks = pattern.match(/(''|[^'])+/g),
  457. literal = pattern.charAt(0) == "'";
  458. dojo.forEach(chunks, function(chunk, i){
  459. if(!chunk){
  460. chunks[i]='';
  461. }else{
  462. chunks[i]=(literal ? applyLiteral : applyPattern)(chunk.replace(/''/g, "'"));
  463. literal = !literal;
  464. }
  465. });
  466. return applyAll(chunks.join(''));
  467. }
  468. function _buildDateTimeRE(tokens, bundle, options, pattern){
  469. pattern = regexp.escapeString(pattern);
  470. if(!options.strict){ pattern = pattern.replace(" a", " ?a"); } // kludge to tolerate no space before am/pm
  471. return pattern.replace(/([a-z])\1*/ig, function(match){
  472. // Build a simple regexp. Avoid captures, which would ruin the tokens list
  473. var s,
  474. c = match.charAt(0),
  475. l = match.length,
  476. p2 = '', p3 = '';
  477. if(options.strict){
  478. if(l > 1){ p2 = '0' + '{'+(l-1)+'}'; }
  479. if(l > 2){ p3 = '0' + '{'+(l-2)+'}'; }
  480. }else{
  481. p2 = '0?'; p3 = '0{0,2}';
  482. }
  483. switch(c){
  484. case 'y':
  485. s = '\\d{2,4}';
  486. break;
  487. case 'M':
  488. s = (l>2) ? '\\S+?' : '1[0-2]|'+p2+'[1-9]';
  489. break;
  490. case 'D':
  491. s = '[12][0-9][0-9]|3[0-5][0-9]|36[0-6]|'+p2+'[1-9][0-9]|'+p3+'[1-9]';
  492. break;
  493. case 'd':
  494. s = '3[01]|[12]\\d|'+p2+'[1-9]';
  495. break;
  496. case 'w':
  497. s = '[1-4][0-9]|5[0-3]|'+p2+'[1-9]';
  498. break;
  499. case 'E':
  500. s = '\\S+';
  501. break;
  502. case 'h': //hour (1-12)
  503. s = '1[0-2]|'+p2+'[1-9]';
  504. break;
  505. case 'k': //hour (0-11)
  506. s = '1[01]|'+p2+'\\d';
  507. break;
  508. case 'H': //hour (0-23)
  509. s = '1\\d|2[0-3]|'+p2+'\\d';
  510. break;
  511. case 'K': //hour (1-24)
  512. s = '1\\d|2[0-4]|'+p2+'[1-9]';
  513. break;
  514. case 'm':
  515. case 's':
  516. s = '[0-5]\\d';
  517. break;
  518. case 'S':
  519. s = '\\d{'+l+'}';
  520. break;
  521. case 'a':
  522. var am = options.am || bundle['dayPeriods-format-wide-am'],
  523. pm = options.pm || bundle['dayPeriods-format-wide-pm'];
  524. s = am + '|' + pm;
  525. if(!options.strict){
  526. if(am != am.toLowerCase()){ s += '|' + am.toLowerCase(); }
  527. if(pm != pm.toLowerCase()){ s += '|' + pm.toLowerCase(); }
  528. if(s.indexOf('.') != -1){ s += '|' + s.replace(/\./g, ""); }
  529. }
  530. s = s.replace(/\./g, "\\.");
  531. break;
  532. default:
  533. // case 'v':
  534. // case 'z':
  535. // case 'Z':
  536. s = ".*";
  537. // console.log("parse of date format, pattern=" + pattern);
  538. }
  539. if(tokens){ tokens.push(match); }
  540. return "(" + s + ")"; // add capture
  541. }).replace(/[\xa0 ]/g, "[\\s\\xa0]"); // normalize whitespace. Need explicit handling of \xa0 for IE.
  542. }
  543. var _customFormats = [];
  544. dojo.date.locale.addCustomFormats = function(/*String*/packageName, /*String*/bundleName){
  545. // summary:
  546. // Add a reference to a bundle containing localized custom formats to be
  547. // used by date/time formatting and parsing routines.
  548. //
  549. // description:
  550. // The user may add custom localized formats where the bundle has properties following the
  551. // same naming convention used by dojo.cldr: `dateFormat-xxxx` / `timeFormat-xxxx`
  552. // The pattern string should match the format used by the CLDR.
  553. // See dojo.date.locale.format() for details.
  554. // The resources must be loaded by dojo.requireLocalization() prior to use
  555. _customFormats.push({pkg:packageName,name:bundleName});
  556. };
  557. dojo.date.locale._getGregorianBundle = function(/*String*/locale){
  558. var gregorian = {};
  559. dojo.forEach(_customFormats, function(desc){
  560. var bundle = dojo.i18n.getLocalization(desc.pkg, desc.name, locale);
  561. gregorian = lang.mixin(gregorian, bundle);
  562. }, this);
  563. return gregorian; /*Object*/
  564. };
  565. dojo.date.locale.addCustomFormats("dojo.cldr","gregorian");
  566. dojo.date.locale.getNames = function(/*String*/item, /*String*/type, /*String?*/context, /*String?*/locale){
  567. // summary:
  568. // Used to get localized strings from dojo.cldr for day or month names.
  569. //
  570. // item:
  571. // 'months' || 'days'
  572. // type:
  573. // 'wide' || 'abbr' || 'narrow' (e.g. "Monday", "Mon", or "M" respectively, in English)
  574. // context:
  575. // 'standAlone' || 'format' (default)
  576. // locale:
  577. // override locale used to find the names
  578. var label,
  579. lookup = dojo.date.locale._getGregorianBundle(locale),
  580. props = [item, context, type];
  581. if(context == 'standAlone'){
  582. var key = props.join('-');
  583. label = lookup[key];
  584. // Fall back to 'format' flavor of name
  585. if(label[0] == 1){ label = undefined; } // kludge, in the absence of real aliasing support in dojo.cldr
  586. }
  587. props[1] = 'format';
  588. // return by copy so changes won't be made accidentally to the in-memory model
  589. return (label || lookup[props.join('-')]).concat(); /*Array*/
  590. };
  591. dojo.date.locale.isWeekend = function(/*Date?*/dateObject, /*String?*/locale){
  592. // summary:
  593. // Determines if the date falls on a weekend, according to local custom.
  594. var weekend = cldr.getWeekend(locale),
  595. day = (dateObject || new Date()).getDay();
  596. if(weekend.end < weekend.start){
  597. weekend.end += 7;
  598. if(day < weekend.start){ day += 7; }
  599. }
  600. return day >= weekend.start && day <= weekend.end; // Boolean
  601. };
  602. // These are used only by format and strftime. Do they need to be public? Which module should they go in?
  603. dojo.date.locale._getDayOfYear = function(/*Date*/dateObject){
  604. // summary: gets the day of the year as represented by dateObject
  605. return date.difference(new Date(dateObject.getFullYear(), 0, 1, dateObject.getHours()), dateObject) + 1; // Number
  606. };
  607. dojo.date.locale._getWeekOfYear = function(/*Date*/dateObject, /*Number*/firstDayOfWeek){
  608. if(arguments.length == 1){ firstDayOfWeek = 0; } // Sunday
  609. var firstDayOfYear = new Date(dateObject.getFullYear(), 0, 1).getDay(),
  610. adj = (firstDayOfYear - firstDayOfWeek + 7) % 7,
  611. week = Math.floor((dojo.date.locale._getDayOfYear(dateObject) + adj - 1) / 7);
  612. // if year starts on the specified day, start counting weeks at 1
  613. if(firstDayOfYear == firstDayOfWeek){ week++; }
  614. return week; // Number
  615. };
  616. return dojo.date.locale;
  617. });