globalize.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  1. /*!
  2. * Globalize
  3. *
  4. * http://github.com/jquery/globalize
  5. *
  6. * Copyright Software Freedom Conservancy, Inc.
  7. * Dual licensed under the MIT or GPL Version 2 licenses.
  8. * http://jquery.org/license
  9. */
  10. (function( window, undefined ) {
  11. var Globalize,
  12. // private variables
  13. regexHex,
  14. regexInfinity,
  15. regexParseFloat,
  16. regexTrim,
  17. // private JavaScript utility functions
  18. arrayIndexOf,
  19. endsWith,
  20. extend,
  21. isArray,
  22. isFunction,
  23. isObject,
  24. startsWith,
  25. trim,
  26. truncate,
  27. zeroPad,
  28. // private Globalization utility functions
  29. appendPreOrPostMatch,
  30. expandFormat,
  31. formatDate,
  32. formatNumber,
  33. getTokenRegExp,
  34. getEra,
  35. getEraYear,
  36. parseExact,
  37. parseNegativePattern;
  38. // Global variable (Globalize) or CommonJS module (globalize)
  39. Globalize = function( cultureSelector ) {
  40. return new Globalize.prototype.init( cultureSelector );
  41. };
  42. if ( typeof require !== "undefined"
  43. && typeof exports !== "undefined"
  44. && typeof module !== "undefined" ) {
  45. // Assume CommonJS
  46. module.exports = Globalize;
  47. } else {
  48. // Export as global variable
  49. window.Globalize = Globalize;
  50. }
  51. Globalize.cultures = {};
  52. Globalize.prototype = {
  53. constructor: Globalize,
  54. init: function( cultureSelector ) {
  55. this.cultures = Globalize.cultures;
  56. this.cultureSelector = cultureSelector;
  57. return this;
  58. }
  59. };
  60. Globalize.prototype.init.prototype = Globalize.prototype;
  61. // 1. When defining a culture, all fields are required except the ones stated as optional.
  62. // 2. Each culture should have a ".calendars" object with at least one calendar named "standard"
  63. // which serves as the default calendar in use by that culture.
  64. // 3. Each culture should have a ".calendar" object which is the current calendar being used,
  65. // it may be dynamically changed at any time to one of the calendars in ".calendars".
  66. Globalize.cultures[ "default" ] = {
  67. // A unique name for the culture in the form <language code>-<country/region code>
  68. name: "en",
  69. // the name of the culture in the english language
  70. englishName: "English",
  71. // the name of the culture in its own language
  72. nativeName: "English",
  73. // whether the culture uses right-to-left text
  74. isRTL: false,
  75. // "language" is used for so-called "specific" cultures.
  76. // For example, the culture "es-CL" means "Spanish, in Chili".
  77. // It represents the Spanish-speaking culture as it is in Chili,
  78. // which might have different formatting rules or even translations
  79. // than Spanish in Spain. A "neutral" culture is one that is not
  80. // specific to a region. For example, the culture "es" is the generic
  81. // Spanish culture, which may be a more generalized version of the language
  82. // that may or may not be what a specific culture expects.
  83. // For a specific culture like "es-CL", the "language" field refers to the
  84. // neutral, generic culture information for the language it is using.
  85. // This is not always a simple matter of the string before the dash.
  86. // For example, the "zh-Hans" culture is netural (Simplified Chinese).
  87. // And the "zh-SG" culture is Simplified Chinese in Singapore, whose lanugage
  88. // field is "zh-CHS", not "zh".
  89. // This field should be used to navigate from a specific culture to it's
  90. // more general, neutral culture. If a culture is already as general as it
  91. // can get, the language may refer to itself.
  92. language: "en",
  93. // numberFormat defines general number formatting rules, like the digits in
  94. // each grouping, the group separator, and how negative numbers are displayed.
  95. numberFormat: {
  96. // [negativePattern]
  97. // Note, numberFormat.pattern has no "positivePattern" unlike percent and currency,
  98. // but is still defined as an array for consistency with them.
  99. // negativePattern: one of "(n)|-n|- n|n-|n -"
  100. pattern: [ "-n" ],
  101. // number of decimal places normally shown
  102. decimals: 2,
  103. // string that separates number groups, as in 1,000,000
  104. ",": ",",
  105. // string that separates a number from the fractional portion, as in 1.99
  106. ".": ".",
  107. // array of numbers indicating the size of each number group.
  108. // TODO: more detailed description and example
  109. groupSizes: [ 3 ],
  110. // symbol used for positive numbers
  111. "+": "+",
  112. // symbol used for negative numbers
  113. "-": "-",
  114. // symbol used for NaN (Not-A-Number)
  115. NaN: "NaN",
  116. // symbol used for Negative Infinity
  117. negativeInfinity: "-Infinity",
  118. // symbol used for Positive Infinity
  119. positiveInfinity: "Infinity",
  120. percent: {
  121. // [negativePattern, positivePattern]
  122. // negativePattern: one of "-n %|-n%|-%n|%-n|%n-|n-%|n%-|-% n|n %-|% n-|% -n|n- %"
  123. // positivePattern: one of "n %|n%|%n|% n"
  124. pattern: [ "-n %", "n %" ],
  125. // number of decimal places normally shown
  126. decimals: 2,
  127. // array of numbers indicating the size of each number group.
  128. // TODO: more detailed description and example
  129. groupSizes: [ 3 ],
  130. // string that separates number groups, as in 1,000,000
  131. ",": ",",
  132. // string that separates a number from the fractional portion, as in 1.99
  133. ".": ".",
  134. // symbol used to represent a percentage
  135. symbol: "%"
  136. },
  137. currency: {
  138. // [negativePattern, positivePattern]
  139. // negativePattern: one of "($n)|-$n|$-n|$n-|(n$)|-n$|n-$|n$-|-n $|-$ n|n $-|$ n-|$ -n|n- $|($ n)|(n $)"
  140. // positivePattern: one of "$n|n$|$ n|n $"
  141. pattern: [ "($n)", "$n" ],
  142. // number of decimal places normally shown
  143. decimals: 2,
  144. // array of numbers indicating the size of each number group.
  145. // TODO: more detailed description and example
  146. groupSizes: [ 3 ],
  147. // string that separates number groups, as in 1,000,000
  148. ",": ",",
  149. // string that separates a number from the fractional portion, as in 1.99
  150. ".": ".",
  151. // symbol used to represent currency
  152. symbol: "$"
  153. }
  154. },
  155. // calendars defines all the possible calendars used by this culture.
  156. // There should be at least one defined with name "standard", and is the default
  157. // calendar used by the culture.
  158. // A calendar contains information about how dates are formatted, information about
  159. // the calendar's eras, a standard set of the date formats,
  160. // translations for day and month names, and if the calendar is not based on the Gregorian
  161. // calendar, conversion functions to and from the Gregorian calendar.
  162. calendars: {
  163. standard: {
  164. // name that identifies the type of calendar this is
  165. name: "Gregorian_USEnglish",
  166. // separator of parts of a date (e.g. "/" in 11/05/1955)
  167. "/": "/",
  168. // separator of parts of a time (e.g. ":" in 05:44 PM)
  169. ":": ":",
  170. // the first day of the week (0 = Sunday, 1 = Monday, etc)
  171. firstDay: 0,
  172. days: {
  173. // full day names
  174. names: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
  175. // abbreviated day names
  176. namesAbbr: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
  177. // shortest day names
  178. namesShort: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ]
  179. },
  180. months: {
  181. // full month names (13 months for lunar calendards -- 13th month should be "" if not lunar)
  182. names: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "" ],
  183. // abbreviated month names
  184. namesAbbr: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "" ]
  185. },
  186. // AM and PM designators in one of these forms:
  187. // The usual view, and the upper and lower case versions
  188. // [ standard, lowercase, uppercase ]
  189. // The culture does not use AM or PM (likely all standard date formats use 24 hour time)
  190. // null
  191. AM: [ "AM", "am", "AM" ],
  192. PM: [ "PM", "pm", "PM" ],
  193. eras: [
  194. // eras in reverse chronological order.
  195. // name: the name of the era in this culture (e.g. A.D., C.E.)
  196. // start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era.
  197. // offset: offset in years from gregorian calendar
  198. {
  199. "name": "A.D.",
  200. "start": null,
  201. "offset": 0
  202. }
  203. ],
  204. // when a two digit year is given, it will never be parsed as a four digit
  205. // year greater than this year (in the appropriate era for the culture)
  206. // Set it as a full year (e.g. 2029) or use an offset format starting from
  207. // the current year: "+19" would correspond to 2029 if the current year 2010.
  208. twoDigitYearMax: 2029,
  209. // set of predefined date and time patterns used by the culture
  210. // these represent the format someone in this culture would expect
  211. // to see given the portions of the date that are shown.
  212. patterns: {
  213. // short date pattern
  214. d: "M/d/yyyy",
  215. // long date pattern
  216. D: "dddd, MMMM dd, yyyy",
  217. // short time pattern
  218. t: "h:mm tt",
  219. // long time pattern
  220. T: "h:mm:ss tt",
  221. // long date, short time pattern
  222. f: "dddd, MMMM dd, yyyy h:mm tt",
  223. // long date, long time pattern
  224. F: "dddd, MMMM dd, yyyy h:mm:ss tt",
  225. // month/day pattern
  226. M: "MMMM dd",
  227. // month/year pattern
  228. Y: "yyyy MMMM",
  229. // S is a sortable format that does not vary by culture
  230. S: "yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss"
  231. }
  232. // optional fields for each calendar:
  233. /*
  234. monthsGenitive:
  235. Same as months but used when the day preceeds the month.
  236. Omit if the culture has no genitive distinction in month names.
  237. For an explaination of genitive months, see http://blogs.msdn.com/michkap/archive/2004/12/25/332259.aspx
  238. convert:
  239. Allows for the support of non-gregorian based calendars. This convert object is used to
  240. to convert a date to and from a gregorian calendar date to handle parsing and formatting.
  241. The two functions:
  242. fromGregorian( date )
  243. Given the date as a parameter, return an array with parts [ year, month, day ]
  244. corresponding to the non-gregorian based year, month, and day for the calendar.
  245. toGregorian( year, month, day )
  246. Given the non-gregorian year, month, and day, return a new Date() object
  247. set to the corresponding date in the gregorian calendar.
  248. */
  249. }
  250. },
  251. // For localized strings
  252. messages: {}
  253. };
  254. Globalize.cultures[ "default" ].calendar = Globalize.cultures[ "default" ].calendars.standard;
  255. Globalize.cultures[ "en" ] = Globalize.cultures[ "default" ];
  256. Globalize.cultureSelector = "en";
  257. //
  258. // private variables
  259. //
  260. regexHex = /^0x[a-f0-9]+$/i;
  261. regexInfinity = /^[+-]?infinity$/i;
  262. regexParseFloat = /^[+-]?\d*\.?\d*(e[+-]?\d+)?$/;
  263. regexTrim = /^\s+|\s+$/g;
  264. //
  265. // private JavaScript utility functions
  266. //
  267. arrayIndexOf = function( array, item ) {
  268. if ( array.indexOf ) {
  269. return array.indexOf( item );
  270. }
  271. for ( var i = 0, length = array.length; i < length; i++ ) {
  272. if ( array[i] === item ) {
  273. return i;
  274. }
  275. }
  276. return -1;
  277. };
  278. endsWith = function( value, pattern ) {
  279. return value.substr( value.length - pattern.length ) === pattern;
  280. };
  281. extend = function( deep ) {
  282. var options, name, src, copy, copyIsArray, clone,
  283. target = arguments[0] || {},
  284. i = 1,
  285. length = arguments.length,
  286. deep = false;
  287. // Handle a deep copy situation
  288. if ( typeof target === "boolean" ) {
  289. deep = target;
  290. target = arguments[1] || {};
  291. // skip the boolean and the target
  292. i = 2;
  293. }
  294. // Handle case when target is a string or something (possible in deep copy)
  295. if ( typeof target !== "object" && !isFunction(target) ) {
  296. target = {};
  297. }
  298. for ( ; i < length; i++ ) {
  299. // Only deal with non-null/undefined values
  300. if ( (options = arguments[ i ]) != null ) {
  301. // Extend the base object
  302. for ( name in options ) {
  303. src = target[ name ];
  304. copy = options[ name ];
  305. // Prevent never-ending loop
  306. if ( target === copy ) {
  307. continue;
  308. }
  309. // Recurse if we're merging plain objects or arrays
  310. if ( deep && copy && ( isObject(copy) || (copyIsArray = isArray(copy)) ) ) {
  311. if ( copyIsArray ) {
  312. copyIsArray = false;
  313. clone = src && isArray(src) ? src : [];
  314. } else {
  315. clone = src && isObject(src) ? src : {};
  316. }
  317. // Never move original objects, clone them
  318. target[ name ] = extend( deep, clone, copy );
  319. // Don't bring in undefined values
  320. } else if ( copy !== undefined ) {
  321. target[ name ] = copy;
  322. }
  323. }
  324. }
  325. }
  326. // Return the modified object
  327. return target;
  328. };
  329. isArray = Array.isArray || function( obj ) {
  330. return Object.prototype.toString.call( obj ) === "[object Array]";
  331. };
  332. isFunction = function( obj ) {
  333. return Object.prototype.toString.call( obj ) === "[object Function]"
  334. }
  335. isObject = function( obj ) {
  336. return Object.prototype.toString.call( obj ) === "[object Object]";
  337. };
  338. startsWith = function( value, pattern ) {
  339. return value.indexOf( pattern ) === 0;
  340. };
  341. trim = function( value ) {
  342. return ( value + "" ).replace( regexTrim, "" );
  343. };
  344. truncate = function( value ) {
  345. return value | 0;
  346. };
  347. zeroPad = function( str, count, left ) {
  348. var l;
  349. for ( l = str.length; l < count; l += 1 ) {
  350. str = ( left ? ("0" + str) : (str + "0") );
  351. }
  352. return str;
  353. };
  354. //
  355. // private Globalization utility functions
  356. //
  357. appendPreOrPostMatch = function( preMatch, strings ) {
  358. // appends pre- and post- token match strings while removing escaped characters.
  359. // Returns a single quote count which is used to determine if the token occurs
  360. // in a string literal.
  361. var quoteCount = 0,
  362. escaped = false;
  363. for ( var i = 0, il = preMatch.length; i < il; i++ ) {
  364. var c = preMatch.charAt( i );
  365. switch ( c ) {
  366. case "\'":
  367. if ( escaped ) {
  368. strings.push( "\'" );
  369. }
  370. else {
  371. quoteCount++;
  372. }
  373. escaped = false;
  374. break;
  375. case "\\":
  376. if ( escaped ) {
  377. strings.push( "\\" );
  378. }
  379. escaped = !escaped;
  380. break;
  381. default:
  382. strings.push( c );
  383. escaped = false;
  384. break;
  385. }
  386. }
  387. return quoteCount;
  388. };
  389. expandFormat = function( cal, format ) {
  390. // expands unspecified or single character date formats into the full pattern.
  391. format = format || "F";
  392. var pattern,
  393. patterns = cal.patterns,
  394. len = format.length;
  395. if ( len === 1 ) {
  396. pattern = patterns[ format ];
  397. if ( !pattern ) {
  398. throw "Invalid date format string \'" + format + "\'.";
  399. }
  400. format = pattern;
  401. }
  402. else if ( len === 2 && format.charAt(0) === "%" ) {
  403. // %X escape format -- intended as a custom format string that is only one character, not a built-in format.
  404. format = format.charAt( 1 );
  405. }
  406. return format;
  407. };
  408. formatDate = function( value, format, culture ) {
  409. var cal = culture.calendar,
  410. convert = cal.convert;
  411. if ( !format || !format.length || format === "i" ) {
  412. var ret;
  413. if ( culture && culture.name.length ) {
  414. if ( convert ) {
  415. // non-gregorian calendar, so we cannot use built-in toLocaleString()
  416. ret = formatDate( value, cal.patterns.F, culture );
  417. }
  418. else {
  419. var eraDate = new Date( value.getTime() ),
  420. era = getEra( value, cal.eras );
  421. eraDate.setFullYear( getEraYear(value, cal, era) );
  422. ret = eraDate.toLocaleString();
  423. }
  424. }
  425. else {
  426. ret = value.toString();
  427. }
  428. return ret;
  429. }
  430. var eras = cal.eras,
  431. sortable = format === "s";
  432. format = expandFormat( cal, format );
  433. // Start with an empty string
  434. ret = [];
  435. var hour,
  436. zeros = [ "0", "00", "000" ],
  437. foundDay,
  438. checkedDay,
  439. dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g,
  440. quoteCount = 0,
  441. tokenRegExp = getTokenRegExp(),
  442. converted;
  443. function padZeros( num, c ) {
  444. var r, s = num + "";
  445. if ( c > 1 && s.length < c ) {
  446. r = ( zeros[c - 2] + s);
  447. return r.substr( r.length - c, c );
  448. }
  449. else {
  450. r = s;
  451. }
  452. return r;
  453. }
  454. function hasDay() {
  455. if ( foundDay || checkedDay ) {
  456. return foundDay;
  457. }
  458. foundDay = dayPartRegExp.test( format );
  459. checkedDay = true;
  460. return foundDay;
  461. }
  462. function getPart( date, part ) {
  463. if ( converted ) {
  464. return converted[ part ];
  465. }
  466. switch ( part ) {
  467. case 0: return date.getFullYear();
  468. case 1: return date.getMonth();
  469. case 2: return date.getDate();
  470. }
  471. }
  472. if ( !sortable && convert ) {
  473. converted = convert.fromGregorian( value );
  474. }
  475. for ( ; ; ) {
  476. // Save the current index
  477. var index = tokenRegExp.lastIndex,
  478. // Look for the next pattern
  479. ar = tokenRegExp.exec( format );
  480. // Append the text before the pattern (or the end of the string if not found)
  481. var preMatch = format.slice( index, ar ? ar.index : format.length );
  482. quoteCount += appendPreOrPostMatch( preMatch, ret );
  483. if ( !ar ) {
  484. break;
  485. }
  486. // do not replace any matches that occur inside a string literal.
  487. if ( quoteCount % 2 ) {
  488. ret.push( ar[0] );
  489. continue;
  490. }
  491. var current = ar[ 0 ],
  492. clength = current.length;
  493. switch ( current ) {
  494. case "ddd":
  495. //Day of the week, as a three-letter abbreviation
  496. case "dddd":
  497. // Day of the week, using the full name
  498. var names = ( clength === 3 ) ? cal.days.namesAbbr : cal.days.names;
  499. ret.push( names[value.getDay()] );
  500. break;
  501. case "d":
  502. // Day of month, without leading zero for single-digit days
  503. case "dd":
  504. // Day of month, with leading zero for single-digit days
  505. foundDay = true;
  506. ret.push(
  507. padZeros( getPart(value, 2), clength )
  508. );
  509. break;
  510. case "MMM":
  511. // Month, as a three-letter abbreviation
  512. case "MMMM":
  513. // Month, using the full name
  514. var part = getPart( value, 1 );
  515. ret.push(
  516. ( cal.monthsGenitive && hasDay() )
  517. ?
  518. cal.monthsGenitive[ clength === 3 ? "namesAbbr" : "names" ][ part ]
  519. :
  520. cal.months[ clength === 3 ? "namesAbbr" : "names" ][ part ]
  521. );
  522. break;
  523. case "M":
  524. // Month, as digits, with no leading zero for single-digit months
  525. case "MM":
  526. // Month, as digits, with leading zero for single-digit months
  527. ret.push(
  528. padZeros( getPart(value, 1) + 1, clength )
  529. );
  530. break;
  531. case "y":
  532. // Year, as two digits, but with no leading zero for years less than 10
  533. case "yy":
  534. // Year, as two digits, with leading zero for years less than 10
  535. case "yyyy":
  536. // Year represented by four full digits
  537. part = converted ? converted[ 0 ] : getEraYear( value, cal, getEra(value, eras), sortable );
  538. if ( clength < 4 ) {
  539. part = part % 100;
  540. }
  541. ret.push(
  542. padZeros( part, clength )
  543. );
  544. break;
  545. case "h":
  546. // Hours with no leading zero for single-digit hours, using 12-hour clock
  547. case "hh":
  548. // Hours with leading zero for single-digit hours, using 12-hour clock
  549. hour = value.getHours() % 12;
  550. if ( hour === 0 ) hour = 12;
  551. ret.push(
  552. padZeros( hour, clength )
  553. );
  554. break;
  555. case "H":
  556. // Hours with no leading zero for single-digit hours, using 24-hour clock
  557. case "HH":
  558. // Hours with leading zero for single-digit hours, using 24-hour clock
  559. ret.push(
  560. padZeros( value.getHours(), clength )
  561. );
  562. break;
  563. case "m":
  564. // Minutes with no leading zero for single-digit minutes
  565. case "mm":
  566. // Minutes with leading zero for single-digit minutes
  567. ret.push(
  568. padZeros( value.getMinutes(), clength )
  569. );
  570. break;
  571. case "s":
  572. // Seconds with no leading zero for single-digit seconds
  573. case "ss":
  574. // Seconds with leading zero for single-digit seconds
  575. ret.push(
  576. padZeros( value.getSeconds(), clength )
  577. );
  578. break;
  579. case "t":
  580. // One character am/pm indicator ("a" or "p")
  581. case "tt":
  582. // Multicharacter am/pm indicator
  583. part = value.getHours() < 12 ? ( cal.AM ? cal.AM[0] : " " ) : ( cal.PM ? cal.PM[0] : " " );
  584. ret.push( clength === 1 ? part.charAt(0) : part );
  585. break;
  586. case "f":
  587. // Deciseconds
  588. case "ff":
  589. // Centiseconds
  590. case "fff":
  591. // Milliseconds
  592. ret.push(
  593. padZeros( value.getMilliseconds(), 3 ).substr( 0, clength )
  594. );
  595. break;
  596. case "z":
  597. // Time zone offset, no leading zero
  598. case "zz":
  599. // Time zone offset with leading zero
  600. hour = value.getTimezoneOffset() / 60;
  601. ret.push(
  602. ( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), clength )
  603. );
  604. break;
  605. case "zzz":
  606. // Time zone offset with leading zero
  607. hour = value.getTimezoneOffset() / 60;
  608. ret.push(
  609. ( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), 2 )
  610. // Hard coded ":" separator, rather than using cal.TimeSeparator
  611. // Repeated here for consistency, plus ":" was already assumed in date parsing.
  612. + ":" + padZeros( Math.abs(value.getTimezoneOffset() % 60), 2 )
  613. );
  614. break;
  615. case "g":
  616. case "gg":
  617. if ( cal.eras ) {
  618. ret.push(
  619. cal.eras[ getEra(value, eras) ].name
  620. );
  621. }
  622. break;
  623. case "/":
  624. ret.push( cal["/"] );
  625. break;
  626. default:
  627. throw "Invalid date format pattern \'" + current + "\'.";
  628. break;
  629. }
  630. }
  631. return ret.join( "" );
  632. };
  633. // formatNumber
  634. (function() {
  635. var expandNumber;
  636. expandNumber = function( number, precision, formatInfo ) {
  637. var groupSizes = formatInfo.groupSizes,
  638. curSize = groupSizes[ 0 ],
  639. curGroupIndex = 1,
  640. factor = Math.pow( 10, precision ),
  641. rounded = Math.round( number * factor ) / factor;
  642. if ( !isFinite(rounded) ) {
  643. rounded = number;
  644. }
  645. number = rounded;
  646. var numberString = number+"",
  647. right = "",
  648. split = numberString.split( /e/i ),
  649. exponent = split.length > 1 ? parseInt( split[1], 10 ) : 0;
  650. numberString = split[ 0 ];
  651. split = numberString.split( "." );
  652. numberString = split[ 0 ];
  653. right = split.length > 1 ? split[ 1 ] : "";
  654. var l;
  655. if ( exponent > 0 ) {
  656. right = zeroPad( right, exponent, false );
  657. numberString += right.slice( 0, exponent );
  658. right = right.substr( exponent );
  659. }
  660. else if ( exponent < 0 ) {
  661. exponent = -exponent;
  662. numberString = zeroPad( numberString, exponent + 1 );
  663. right = numberString.slice( -exponent, numberString.length ) + right;
  664. numberString = numberString.slice( 0, -exponent );
  665. }
  666. if ( precision > 0 ) {
  667. right = formatInfo[ "." ] +
  668. ( (right.length > precision) ? right.slice(0, precision) : zeroPad(right, precision) );
  669. }
  670. else {
  671. right = "";
  672. }
  673. var stringIndex = numberString.length - 1,
  674. sep = formatInfo[ "," ],
  675. ret = "";
  676. while ( stringIndex >= 0 ) {
  677. if ( curSize === 0 || curSize > stringIndex ) {
  678. return numberString.slice( 0, stringIndex + 1 ) + ( ret.length ? (sep + ret + right) : right );
  679. }
  680. ret = numberString.slice( stringIndex - curSize + 1, stringIndex + 1 ) + ( ret.length ? (sep + ret) : "" );
  681. stringIndex -= curSize;
  682. if ( curGroupIndex < groupSizes.length ) {
  683. curSize = groupSizes[ curGroupIndex ];
  684. curGroupIndex++;
  685. }
  686. }
  687. return numberString.slice( 0, stringIndex + 1 ) + sep + ret + right;
  688. };
  689. formatNumber = function( value, format, culture ) {
  690. if ( !isFinite(value) ) {
  691. if ( value === Infinity ) {
  692. return culture.numberFormat.positiveInfinity;
  693. }
  694. if ( value === -Infinity ) {
  695. return culture.numberFormat.negativeInfinity;
  696. }
  697. return culture.numberFormat.NaN;
  698. }
  699. if ( !format || format === "i" ) {
  700. return culture.name.length ? value.toLocaleString() : value.toString();
  701. }
  702. format = format || "D";
  703. var nf = culture.numberFormat,
  704. number = Math.abs( value ),
  705. precision = -1,
  706. pattern;
  707. if ( format.length > 1 ) precision = parseInt( format.slice(1), 10 );
  708. var current = format.charAt( 0 ).toUpperCase(),
  709. formatInfo;
  710. switch ( current ) {
  711. case "D":
  712. pattern = "n";
  713. number = truncate( number );
  714. if ( precision !== -1 ) {
  715. number = zeroPad( "" + number, precision, true );
  716. }
  717. if ( value < 0 ) number = "-" + number;
  718. break;
  719. case "N":
  720. formatInfo = nf;
  721. // fall through
  722. case "C":
  723. formatInfo = formatInfo || nf.currency;
  724. // fall through
  725. case "P":
  726. formatInfo = formatInfo || nf.percent;
  727. pattern = value < 0 ? formatInfo.pattern[ 0 ] : ( formatInfo.pattern[1] || "n" );
  728. if ( precision === -1 ) precision = formatInfo.decimals;
  729. number = expandNumber( number * (current === "P" ? 100 : 1), precision, formatInfo );
  730. break;
  731. default:
  732. throw "Bad number format specifier: " + current;
  733. }
  734. var patternParts = /n|\$|-|%/g,
  735. ret = "";
  736. for ( ; ; ) {
  737. var index = patternParts.lastIndex,
  738. ar = patternParts.exec( pattern );
  739. ret += pattern.slice( index, ar ? ar.index : pattern.length );
  740. if ( !ar ) {
  741. break;
  742. }
  743. switch ( ar[0] ) {
  744. case "n":
  745. ret += number;
  746. break;
  747. case "$":
  748. ret += nf.currency.symbol;
  749. break;
  750. case "-":
  751. // don't make 0 negative
  752. if ( /[1-9]/.test(number) ) {
  753. ret += nf[ "-" ];
  754. }
  755. break;
  756. case "%":
  757. ret += nf.percent.symbol;
  758. break;
  759. }
  760. }
  761. return ret;
  762. };
  763. }());
  764. getTokenRegExp = function() {
  765. // regular expression for matching date and time tokens in format strings.
  766. return /\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g;
  767. };
  768. getEra = function( date, eras ) {
  769. if ( !eras ) return 0;
  770. var start, ticks = date.getTime();
  771. for ( var i = 0, l = eras.length; i < l; i++ ) {
  772. start = eras[ i ].start;
  773. if ( start === null || ticks >= start ) {
  774. return i;
  775. }
  776. }
  777. return 0;
  778. };
  779. getEraYear = function( date, cal, era, sortable ) {
  780. var year = date.getFullYear();
  781. if ( !sortable && cal.eras ) {
  782. // convert normal gregorian year to era-shifted gregorian
  783. // year by subtracting the era offset
  784. year -= cal.eras[ era ].offset;
  785. }
  786. return year;
  787. };
  788. // parseExact
  789. (function() {
  790. var expandYear,
  791. getDayIndex,
  792. getMonthIndex,
  793. getParseRegExp,
  794. outOfRange,
  795. toUpper,
  796. toUpperArray;
  797. expandYear = function( cal, year ) {
  798. // expands 2-digit year into 4 digits.
  799. var now = new Date(),
  800. era = getEra( now );
  801. if ( year < 100 ) {
  802. var twoDigitYearMax = cal.twoDigitYearMax;
  803. twoDigitYearMax = typeof twoDigitYearMax === "string" ? new Date().getFullYear() % 100 + parseInt( twoDigitYearMax, 10 ) : twoDigitYearMax;
  804. var curr = getEraYear( now, cal, era );
  805. year += curr - ( curr % 100 );
  806. if ( year > twoDigitYearMax ) {
  807. year -= 100;
  808. }
  809. }
  810. return year;
  811. };
  812. getDayIndex = function ( cal, value, abbr ) {
  813. var ret,
  814. days = cal.days,
  815. upperDays = cal._upperDays;
  816. if ( !upperDays ) {
  817. cal._upperDays = upperDays = [
  818. toUpperArray( days.names ),
  819. toUpperArray( days.namesAbbr ),
  820. toUpperArray( days.namesShort )
  821. ];
  822. }
  823. value = toUpper( value );
  824. if ( abbr ) {
  825. ret = arrayIndexOf( upperDays[1], value );
  826. if ( ret === -1 ) {
  827. ret = arrayIndexOf( upperDays[2], value );
  828. }
  829. }
  830. else {
  831. ret = arrayIndexOf( upperDays[0], value );
  832. }
  833. return ret;
  834. };
  835. getMonthIndex = function( cal, value, abbr ) {
  836. var months = cal.months,
  837. monthsGen = cal.monthsGenitive || cal.months,
  838. upperMonths = cal._upperMonths,
  839. upperMonthsGen = cal._upperMonthsGen;
  840. if ( !upperMonths ) {
  841. cal._upperMonths = upperMonths = [
  842. toUpperArray( months.names ),
  843. toUpperArray( months.namesAbbr )
  844. ];
  845. cal._upperMonthsGen = upperMonthsGen = [
  846. toUpperArray( monthsGen.names ),
  847. toUpperArray( monthsGen.namesAbbr )
  848. ];
  849. }
  850. value = toUpper( value );
  851. var i = arrayIndexOf( abbr ? upperMonths[1] : upperMonths[0], value );
  852. if ( i < 0 ) {
  853. i = arrayIndexOf( abbr ? upperMonthsGen[1] : upperMonthsGen[0], value );
  854. }
  855. return i;
  856. };
  857. getParseRegExp = function( cal, format ) {
  858. // converts a format string into a regular expression with groups that
  859. // can be used to extract date fields from a date string.
  860. // check for a cached parse regex.
  861. var re = cal._parseRegExp;
  862. if ( !re ) {
  863. cal._parseRegExp = re = {};
  864. }
  865. else {
  866. var reFormat = re[ format ];
  867. if ( reFormat ) {
  868. return reFormat;
  869. }
  870. }
  871. // expand single digit formats, then escape regular expression characters.
  872. var expFormat = expandFormat( cal, format ).replace( /([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1" ),
  873. regexp = [ "^" ],
  874. groups = [],
  875. index = 0,
  876. quoteCount = 0,
  877. tokenRegExp = getTokenRegExp(),
  878. match;
  879. // iterate through each date token found.
  880. while ( (match = tokenRegExp.exec(expFormat)) !== null ) {
  881. var preMatch = expFormat.slice( index, match.index );
  882. index = tokenRegExp.lastIndex;
  883. // don't replace any matches that occur inside a string literal.
  884. quoteCount += appendPreOrPostMatch( preMatch, regexp );
  885. if ( quoteCount % 2 ) {
  886. regexp.push( match[0] );
  887. continue;
  888. }
  889. // add a regex group for the token.
  890. var m = match[ 0 ],
  891. len = m.length,
  892. add;
  893. switch ( m ) {
  894. case "dddd": case "ddd":
  895. case "MMMM": case "MMM":
  896. case "gg": case "g":
  897. add = "(\\D+)";
  898. break;
  899. case "tt": case "t":
  900. add = "(\\D*)";
  901. break;
  902. case "yyyy":
  903. case "fff":
  904. case "ff":
  905. case "f":
  906. add = "(\\d{" + len + "})";
  907. break;
  908. case "dd": case "d":
  909. case "MM": case "M":
  910. case "yy": case "y":
  911. case "HH": case "H":
  912. case "hh": case "h":
  913. case "mm": case "m":
  914. case "ss": case "s":
  915. add = "(\\d\\d?)";
  916. break;
  917. case "zzz":
  918. add = "([+-]?\\d\\d?:\\d{2})";
  919. break;
  920. case "zz": case "z":
  921. add = "([+-]?\\d\\d?)";
  922. break;
  923. case "/":
  924. add = "(\\" + cal[ "/" ] + ")";
  925. break;
  926. default:
  927. throw "Invalid date format pattern \'" + m + "\'.";
  928. break;
  929. }
  930. if ( add ) {
  931. regexp.push( add );
  932. }
  933. groups.push( match[0] );
  934. }
  935. appendPreOrPostMatch( expFormat.slice(index), regexp );
  936. regexp.push( "$" );
  937. // allow whitespace to differ when matching formats.
  938. var regexpStr = regexp.join( "" ).replace( /\s+/g, "\\s+" ),
  939. parseRegExp = { "regExp": regexpStr, "groups": groups };
  940. // cache the regex for this format.
  941. return re[ format ] = parseRegExp;
  942. };
  943. outOfRange = function( value, low, high ) {
  944. return value < low || value > high;
  945. };
  946. toUpper = function( value ) {
  947. // "he-IL" has non-breaking space in weekday names.
  948. return value.split( "\u00A0" ).join( " " ).toUpperCase();
  949. };
  950. toUpperArray = function( arr ) {
  951. var results = [];
  952. for ( var i = 0, l = arr.length; i < l; i++ ) {
  953. results[ i ] = toUpper( arr[i] );
  954. }
  955. return results;
  956. };
  957. parseExact = function( value, format, culture ) {
  958. // try to parse the date string by matching against the format string
  959. // while using the specified culture for date field names.
  960. value = trim( value );
  961. var cal = culture.calendar,
  962. // convert date formats into regular expressions with groupings.
  963. // use the regexp to determine the input format and extract the date fields.
  964. parseInfo = getParseRegExp( cal, format ),
  965. match = new RegExp( parseInfo.regExp ).exec( value );
  966. if ( match === null ) {
  967. return null;
  968. }
  969. // found a date format that matches the input.
  970. var groups = parseInfo.groups,
  971. era = null, year = null, month = null, date = null, weekDay = null,
  972. hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null,
  973. pmHour = false;
  974. // iterate the format groups to extract and set the date fields.
  975. for ( var j = 0, jl = groups.length; j < jl; j++ ) {
  976. var matchGroup = match[ j + 1 ];
  977. if ( matchGroup ) {
  978. var current = groups[ j ],
  979. clength = current.length,
  980. matchInt = parseInt( matchGroup, 10 );
  981. switch ( current ) {
  982. case "dd": case "d":
  983. // Day of month.
  984. date = matchInt;
  985. // check that date is generally in valid range, also checking overflow below.
  986. if ( outOfRange(date, 1, 31) ) return null;
  987. break;
  988. case "MMM": case "MMMM":
  989. month = getMonthIndex( cal, matchGroup, clength === 3 );
  990. if ( outOfRange(month, 0, 11) ) return null;
  991. break;
  992. case "M": case "MM":
  993. // Month.
  994. month = matchInt - 1;
  995. if ( outOfRange(month, 0, 11) ) return null;
  996. break;
  997. case "y": case "yy":
  998. case "yyyy":
  999. year = clength < 4 ? expandYear( cal, matchInt ) : matchInt;
  1000. if ( outOfRange(year, 0, 9999) ) return null;
  1001. break;
  1002. case "h": case "hh":
  1003. // Hours (12-hour clock).
  1004. hour = matchInt;
  1005. if ( hour === 12 ) hour = 0;
  1006. if ( outOfRange(hour, 0, 11) ) return null;
  1007. break;
  1008. case "H": case "HH":
  1009. // Hours (24-hour clock).
  1010. hour = matchInt;
  1011. if ( outOfRange(hour, 0, 23) ) return null;
  1012. break;
  1013. case "m": case "mm":
  1014. // Minutes.
  1015. min = matchInt;
  1016. if ( outOfRange(min, 0, 59) ) return null;
  1017. break;
  1018. case "s": case "ss":
  1019. // Seconds.
  1020. sec = matchInt;
  1021. if ( outOfRange(sec, 0, 59) ) return null;
  1022. break;
  1023. case "tt": case "t":
  1024. // AM/PM designator.
  1025. // see if it is standard, upper, or lower case PM. If not, ensure it is at least one of
  1026. // the AM tokens. If not, fail the parse for this format.
  1027. pmHour = cal.PM && ( matchGroup === cal.PM[0] || matchGroup === cal.PM[1] || matchGroup === cal.PM[2] );
  1028. if (
  1029. !pmHour && (
  1030. !cal.AM || ( matchGroup !== cal.AM[0] && matchGroup !== cal.AM[1] && matchGroup !== cal.AM[2] )
  1031. )
  1032. ) return null;
  1033. break;
  1034. case "f":
  1035. // Deciseconds.
  1036. case "ff":
  1037. // Centiseconds.
  1038. case "fff":
  1039. // Milliseconds.
  1040. msec = matchInt * Math.pow( 10, 3 - clength );
  1041. if ( outOfRange(msec, 0, 999) ) return null;
  1042. break;
  1043. case "ddd":
  1044. // Day of week.
  1045. case "dddd":
  1046. // Day of week.
  1047. weekDay = getDayIndex( cal, matchGroup, clength === 3 );
  1048. if ( outOfRange(weekDay, 0, 6) ) return null;
  1049. break;
  1050. case "zzz":
  1051. // Time zone offset in +/- hours:min.
  1052. var offsets = matchGroup.split( /:/ );
  1053. if ( offsets.length !== 2 ) return null;
  1054. hourOffset = parseInt( offsets[0], 10 );
  1055. if ( outOfRange(hourOffset, -12, 13) ) return null;
  1056. var minOffset = parseInt( offsets[1], 10 );
  1057. if ( outOfRange(minOffset, 0, 59) ) return null;
  1058. tzMinOffset = ( hourOffset * 60 ) + ( startsWith(matchGroup, "-") ? -minOffset : minOffset );
  1059. break;
  1060. case "z": case "zz":
  1061. // Time zone offset in +/- hours.
  1062. hourOffset = matchInt;
  1063. if ( outOfRange(hourOffset, -12, 13) ) return null;
  1064. tzMinOffset = hourOffset * 60;
  1065. break;
  1066. case "g": case "gg":
  1067. var eraName = matchGroup;
  1068. if ( !eraName || !cal.eras ) return null;
  1069. eraName = trim( eraName.toLowerCase() );
  1070. for ( var i = 0, l = cal.eras.length; i < l; i++ ) {
  1071. if ( eraName === cal.eras[i].name.toLowerCase() ) {
  1072. era = i;
  1073. break;
  1074. }
  1075. }
  1076. // could not find an era with that name
  1077. if ( era === null ) return null;
  1078. break;
  1079. }
  1080. }
  1081. }
  1082. var result = new Date(), defaultYear, convert = cal.convert;
  1083. defaultYear = convert ? convert.fromGregorian( result )[ 0 ] : result.getFullYear();
  1084. if ( year === null ) {
  1085. year = defaultYear;
  1086. }
  1087. else if ( cal.eras ) {
  1088. // year must be shifted to normal gregorian year
  1089. // but not if year was not specified, its already normal gregorian
  1090. // per the main if clause above.
  1091. year += cal.eras[( era || 0 )].offset;
  1092. }
  1093. // set default day and month to 1 and January, so if unspecified, these are the defaults
  1094. // instead of the current day/month.
  1095. if ( month === null ) {
  1096. month = 0;
  1097. }
  1098. if ( date === null ) {
  1099. date = 1;
  1100. }
  1101. // now have year, month, and date, but in the culture's calendar.
  1102. // convert to gregorian if necessary
  1103. if ( convert ) {
  1104. result = convert.toGregorian( year, month, date );
  1105. // conversion failed, must be an invalid match
  1106. if ( result === null ) return null;
  1107. }
  1108. else {
  1109. // have to set year, month and date together to avoid overflow based on current date.
  1110. result.setFullYear( year, month, date );
  1111. // check to see if date overflowed for specified month (only checked 1-31 above).
  1112. if ( result.getDate() !== date ) return null;
  1113. // invalid day of week.
  1114. if ( weekDay !== null && result.getDay() !== weekDay ) {
  1115. return null;
  1116. }
  1117. }
  1118. // if pm designator token was found make sure the hours fit the 24-hour clock.
  1119. if ( pmHour && hour < 12 ) {
  1120. hour += 12;
  1121. }
  1122. result.setHours( hour, min, sec, msec );
  1123. if ( tzMinOffset !== null ) {
  1124. // adjust timezone to utc before applying local offset.
  1125. var adjustedMin = result.getMinutes() - ( tzMinOffset + result.getTimezoneOffset() );
  1126. // Safari limits hours and minutes to the range of -127 to 127. We need to use setHours
  1127. // to ensure both these fields will not exceed this range. adjustedMin will range
  1128. // somewhere between -1440 and 1500, so we only need to split this into hours.
  1129. result.setHours( result.getHours() + parseInt(adjustedMin / 60, 10), adjustedMin % 60 );
  1130. }
  1131. return result;
  1132. };
  1133. }());
  1134. parseNegativePattern = function( value, nf, negativePattern ) {
  1135. var neg = nf[ "-" ],
  1136. pos = nf[ "+" ],
  1137. ret;
  1138. switch ( negativePattern ) {
  1139. case "n -":
  1140. neg = " " + neg;
  1141. pos = " " + pos;
  1142. // fall through
  1143. case "n-":
  1144. if ( endsWith(value, neg) ) {
  1145. ret = [ "-", value.substr(0, value.length - neg.length) ];
  1146. }
  1147. else if ( endsWith(value, pos) ) {
  1148. ret = [ "+", value.substr(0, value.length - pos.length) ];
  1149. }
  1150. break;
  1151. case "- n":
  1152. neg += " ";
  1153. pos += " ";
  1154. // fall through
  1155. case "-n":
  1156. if ( startsWith(value, neg) ) {
  1157. ret = [ "-", value.substr(neg.length) ];
  1158. }
  1159. else if ( startsWith(value, pos) ) {
  1160. ret = [ "+", value.substr(pos.length) ];
  1161. }
  1162. break;
  1163. case "(n)":
  1164. if ( startsWith(value, "(") && endsWith(value, ")") ) {
  1165. ret = [ "-", value.substr(1, value.length - 2) ];
  1166. }
  1167. break;
  1168. }
  1169. return ret || [ "", value ];
  1170. };
  1171. //
  1172. // public instance functions
  1173. //
  1174. Globalize.prototype.findClosestCulture = function( cultureSelector ) {
  1175. return Globalize.findClosestCulture.call( this, cultureSelector );
  1176. };
  1177. Globalize.prototype.format = function( value, format, cultureSelector ) {
  1178. return Globalize.format.call( this, value, format, cultureSelector );
  1179. };
  1180. Globalize.prototype.localize = function( key, cultureSelector ) {
  1181. return Globalize.localize.call( this, key, cultureSelector );
  1182. };
  1183. Globalize.prototype.parseInt = function( value, radix, cultureSelector ) {
  1184. return Globalize.parseInt.call( this, value, radix, cultureSelector );
  1185. };
  1186. Globalize.prototype.parseFloat = function( value, radix, cultureSelector ) {
  1187. return Globalize.parseFloat.call( this, value, radix, cultureSelector );
  1188. };
  1189. Globalize.prototype.culture = function( cultureSelector ) {
  1190. return Globalize.culture.call( this, cultureSelector );
  1191. };
  1192. //
  1193. // public singleton functions
  1194. //
  1195. Globalize.addCultureInfo = function( cultureName, baseCultureName, info ) {
  1196. var base = {},
  1197. isNew = false;
  1198. if ( typeof cultureName !== "string" ) {
  1199. // cultureName argument is optional string. If not specified, assume info is first
  1200. // and only argument. Specified info deep-extends current culture.
  1201. info = cultureName;
  1202. cultureName = this.culture().name;
  1203. base = this.cultures[ cultureName ];
  1204. } else if ( typeof baseCultureName !== "string" ) {
  1205. // baseCultureName argument is optional string. If not specified, assume info is second
  1206. // argument. Specified info deep-extends specified culture.
  1207. // If specified culture does not exist, create by deep-extending default
  1208. info = baseCultureName;
  1209. isNew = ( this.cultures[ cultureName ] == null );
  1210. base = this.cultures[ cultureName ] || this.cultures[ "default" ];
  1211. } else {
  1212. // cultureName and baseCultureName specified. Assume a new culture is being created
  1213. // by deep-extending an specified base culture
  1214. isNew = true;
  1215. base = this.cultures[ baseCultureName ];
  1216. }
  1217. this.cultures[ cultureName ] = extend(true, {},
  1218. base,
  1219. info
  1220. );
  1221. // Make the standard calendar the current culture if it's a new culture
  1222. if ( isNew ) {
  1223. this.cultures[ cultureName ].calendar = this.cultures[ cultureName ].calendars.standard;
  1224. }
  1225. };
  1226. Globalize.findClosestCulture = function( name ) {
  1227. var match;
  1228. if ( !name ) {
  1229. return this.cultures[ this.cultureSelector ] || this.cultures[ "default" ];
  1230. }
  1231. if ( typeof name === "string" ) {
  1232. name = name.split( "," );
  1233. }
  1234. if ( isArray(name) ) {
  1235. var lang,
  1236. cultures = this.cultures,
  1237. list = name,
  1238. i, l = list.length,
  1239. prioritized = [];
  1240. for ( i = 0; i < l; i++ ) {
  1241. name = trim( list[i] );
  1242. var pri, parts = name.split( ";" );
  1243. lang = trim( parts[0] );
  1244. if ( parts.length === 1 ) {
  1245. pri = 1;
  1246. }
  1247. else {
  1248. name = trim( parts[1] );
  1249. if ( name.indexOf("q=") === 0 ) {
  1250. name = name.substr( 2 );
  1251. pri = parseFloat( name );
  1252. pri = isNaN( pri ) ? 0 : pri;
  1253. }
  1254. else {
  1255. pri = 1;
  1256. }
  1257. }
  1258. prioritized.push({ lang: lang, pri: pri });
  1259. }
  1260. prioritized.sort(function( a, b ) {
  1261. return a.pri < b.pri ? 1 : -1;
  1262. });
  1263. // exact match
  1264. for ( i = 0; i < l; i++ ) {
  1265. lang = prioritized[ i ].lang;
  1266. match = cultures[ lang ];
  1267. if ( match ) {
  1268. return match;
  1269. }
  1270. }
  1271. // neutral language match
  1272. for ( i = 0; i < l; i++ ) {
  1273. lang = prioritized[ i ].lang;
  1274. do {
  1275. var index = lang.lastIndexOf( "-" );
  1276. if ( index === -1 ) {
  1277. break;
  1278. }
  1279. // strip off the last part. e.g. en-US => en
  1280. lang = lang.substr( 0, index );
  1281. match = cultures[ lang ];
  1282. if ( match ) {
  1283. return match;
  1284. }
  1285. }
  1286. while ( 1 );
  1287. }
  1288. // last resort: match first culture using that language
  1289. for ( i = 0; i < l; i++ ) {
  1290. lang = prioritized[ i ].lang;
  1291. for ( var cultureKey in cultures ) {
  1292. var culture = cultures[ cultureKey ];
  1293. if ( culture.language == lang ) {
  1294. return culture;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. else if ( typeof name === "object" ) {
  1300. return name;
  1301. }
  1302. return match || null;
  1303. };
  1304. Globalize.format = function( value, format, cultureSelector ) {
  1305. culture = this.findClosestCulture( cultureSelector );
  1306. if ( value instanceof Date ) {
  1307. value = formatDate( value, format, culture );
  1308. }
  1309. else if ( typeof value === "number" ) {
  1310. value = formatNumber( value, format, culture );
  1311. }
  1312. return value;
  1313. };
  1314. Globalize.localize = function( key, cultureSelector ) {
  1315. return this.findClosestCulture( cultureSelector ).messages[ key ] ||
  1316. this.cultures[ "default" ].messages[ key ];
  1317. };
  1318. Globalize.parseDate = function( value, formats, culture ) {
  1319. culture = this.findClosestCulture( culture );
  1320. var date, prop, patterns;
  1321. if ( formats ) {
  1322. if ( typeof formats === "string" ) {
  1323. formats = [ formats ];
  1324. }
  1325. if ( formats.length ) {
  1326. for ( var i = 0, l = formats.length; i < l; i++ ) {
  1327. var format = formats[ i ];
  1328. if ( format ) {
  1329. date = parseExact( value, format, culture );
  1330. if ( date ) {
  1331. break;
  1332. }
  1333. }
  1334. }
  1335. }
  1336. } else {
  1337. patterns = culture.calendar.patterns;
  1338. for ( prop in patterns ) {
  1339. date = parseExact( value, patterns[prop], culture );
  1340. if ( date ) {
  1341. break;
  1342. }
  1343. }
  1344. }
  1345. return date || null;
  1346. };
  1347. Globalize.parseInt = function( value, radix, cultureSelector ) {
  1348. return truncate( Globalize.parseFloat(value, radix, cultureSelector) );
  1349. };
  1350. Globalize.parseFloat = function( value, radix, cultureSelector ) {
  1351. // radix argument is optional
  1352. if ( typeof radix !== "number" ) {
  1353. cultureSelector = radix;
  1354. radix = 10;
  1355. }
  1356. var culture = this.findClosestCulture( cultureSelector );
  1357. var ret = NaN,
  1358. nf = culture.numberFormat;
  1359. if ( value.indexOf(culture.numberFormat.currency.symbol) > -1 ) {
  1360. // remove currency symbol
  1361. value = value.replace( culture.numberFormat.currency.symbol, "" );
  1362. // replace decimal seperator
  1363. value = value.replace( culture.numberFormat.currency["."], culture.numberFormat["."] );
  1364. }
  1365. // trim leading and trailing whitespace
  1366. value = trim( value );
  1367. // allow infinity or hexidecimal
  1368. if ( regexInfinity.test(value) ) {
  1369. ret = parseFloat( value );
  1370. }
  1371. else if ( !radix && regexHex.test(value) ) {
  1372. ret = parseInt( value, 16 );
  1373. }
  1374. else {
  1375. // determine sign and number
  1376. var signInfo = parseNegativePattern( value, nf, nf.pattern[0] ),
  1377. sign = signInfo[ 0 ],
  1378. num = signInfo[ 1 ];
  1379. // #44 - try parsing as "(n)"
  1380. if ( sign === "" && nf.pattern[0] !== "(n)" ) {
  1381. signInfo = parseNegativePattern( value, nf, "(n)" );
  1382. sign = signInfo[ 0 ];
  1383. num = signInfo[ 1 ];
  1384. }
  1385. // try parsing as "-n"
  1386. if ( sign === "" && nf.pattern[0] !== "-n" ) {
  1387. signInfo = parseNegativePattern( value, nf, "-n" );
  1388. sign = signInfo[ 0 ];
  1389. num = signInfo[ 1 ];
  1390. }
  1391. sign = sign || "+";
  1392. // determine exponent and number
  1393. var exponent,
  1394. intAndFraction,
  1395. exponentPos = num.indexOf( "e" );
  1396. if ( exponentPos < 0 ) exponentPos = num.indexOf( "E" );
  1397. if ( exponentPos < 0 ) {
  1398. intAndFraction = num;
  1399. exponent = null;
  1400. }
  1401. else {
  1402. intAndFraction = num.substr( 0, exponentPos );
  1403. exponent = num.substr( exponentPos + 1 );
  1404. }
  1405. // determine decimal position
  1406. var integer,
  1407. fraction,
  1408. decSep = nf[ "." ],
  1409. decimalPos = intAndFraction.indexOf( decSep );
  1410. if ( decimalPos < 0 ) {
  1411. integer = intAndFraction;
  1412. fraction = null;
  1413. }
  1414. else {
  1415. integer = intAndFraction.substr( 0, decimalPos );
  1416. fraction = intAndFraction.substr( decimalPos + decSep.length );
  1417. }
  1418. // handle groups (e.g. 1,000,000)
  1419. var groupSep = nf[ "," ];
  1420. integer = integer.split( groupSep ).join( "" );
  1421. var altGroupSep = groupSep.replace( /\u00A0/g, " " );
  1422. if ( groupSep !== altGroupSep ) {
  1423. integer = integer.split( altGroupSep ).join( "" );
  1424. }
  1425. // build a natively parsable number string
  1426. var p = sign + integer;
  1427. if ( fraction !== null ) {
  1428. p += "." + fraction;
  1429. }
  1430. if ( exponent !== null ) {
  1431. // exponent itself may have a number patternd
  1432. var expSignInfo = parseNegativePattern( exponent, nf, "-n" );
  1433. p += "e" + ( expSignInfo[0] || "+" ) + expSignInfo[ 1 ];
  1434. }
  1435. if ( regexParseFloat.test(p) ) {
  1436. ret = parseFloat( p );
  1437. }
  1438. }
  1439. return ret;
  1440. };
  1441. Globalize.culture = function( cultureSelector ) {
  1442. // setter
  1443. if ( typeof cultureSelector !== "undefined" ) {
  1444. this.cultureSelector = cultureSelector;
  1445. }
  1446. // getter
  1447. return this.findClosestCulture( cultureSelector ) || this.culture[ "default" ];
  1448. };
  1449. }( this ));