Prvi commit

This commit is contained in:
David Štaleker
2023-05-12 09:00:07 +02:00
parent d3ffe93e42
commit 03b92525d7
14757 changed files with 9251133 additions and 53 deletions

View File

@@ -0,0 +1,28 @@
## [new] Globalize( locale|cldr )
Create a Globalize instance.
### Parameters
#### locale|cldr
Locale string or [Cldr instance](https://github.com/rxaviers/cldrjs) of the instance.
### Example
Prior to creating any Globalize instance, you must load `cldr/supplemental/likelySubtags.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
var en = new Globalize( "en" );
// You can optionally omit the `new` operator.
var pt = Globalize( "pt" );
en.formatNumber( 3.1415 );
// > 3.142
pt.formatNumber( 3.1415 );
// > 3,142
```

View File

@@ -0,0 +1,96 @@
## Globalize.load( cldrJSONData, ... )
This method allows you to load CLDR JSON locale data. `Globalize.load()` is a proxy to `Cldr.load()`.
This method can be called as many times as needed. All passed JSON objects are deeply merged internally.
For more information, see https://github.com/rxaviers/cldrjs#readme.
### Parameters
#### cldrJSONData
A JSON object with CLDR data. See [Getting Started](#../../../README.md#2-cldr-content) for more information.
### Example
```javascript
Globalize.load({
"main": {
"en": {
"identity": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"generation": {
"_date": "$Date: 2014-03-13 22:27:12 -0500 (Thu, 13 Mar 2014) $"
},
"language": "en"
},
"dates": {
"calendars": {
"gregorian": {
"months": {
"format": {
"abbreviated": {
"1": "Jan",
"2": "Feb",
"3": "Mar",
"4": "Apr",
"5": "May",
"6": "Jun",
"7": "Jul",
"8": "Aug",
"9": "Sep",
"10": "Oct",
"11": "Nov",
"12": "Dec"
}
}
},
"dayPeriods": {
"format": {
"wide": {
"am": "AM",
"am-alt-variant": "am",
"noon": "noon",
"pm": "PM",
"pm-alt-variant": "pm"
}
}
},
"dateFormats": {
"medium": "MMM d, y"
},
"timeFormats": {
"medium": "h:mm:ss a",
},
"dateTimeFormats": {
"medium": "{1}, {0}"
}
}
}
},
"numbers": {
"defaultNumberingSystem": "latn",
"symbols-numberSystem-latn": {
"group": ","
},
"decimalFormats-numberSystem-latn": {
"standard": "#,##0.###"
}
}
}
},
"supplemental": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"likelySubtags": {
"en": "en-Latn-US",
}
}
});
```

View File

@@ -0,0 +1,43 @@
## Globalize.locale( [locale|cldr] )
Set default locale, or get it if locale argument is omitted.
Return the default [Cldr instance](https://github.com/rxaviers/cldrjs).
An application that supports globalization and/or localization will need to have a way to determine the user's preference. Attempting to automatically determine the appropriate locale is useful, but it is good practice to always offer the user a choice, by whatever means.
Whatever your mechanism, it is likely that you will have to correlate the user's preferences with the list of locale data supported in the app. This method allows you to select the best match given the locale data that you have included and to set the Globalize locale to the one which the user prefers.
LanguageMatching TBD (CLDR's spec http://www.unicode.org/reports/tr35/#LanguageMatching).
### Parameters
#### locale|cldr
- The locale string, e.g., `"en"`, `"pt-BR"`, or `"zh-Hant-TW"`. Or,
- The [Cldr instance](https://github.com/rxaviers/cldrjs), e.g., new `Cldr( "en" )`.
### Example
Prior to using this function, you must load `cldr/supplemental/likelySubtags.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
// Set "pt" as our default locale.
Globalize.locale( "pt" );
// Get default locale.
Globalize.locale();
// > {
// attributes: {
// "languageId": "pt",
// "maxLanguageId": "pt_Latn_BR",
// "language": "pt",
// "script": "Latn",
// "territory": "BR",
// "region": "BR"
// },
// some more stuff...
// }
```

View File

@@ -0,0 +1,196 @@
## .currencyFormatter( currency [, options] ) ➜ function( value )
Return a function that formats a `currency` according to the given `options` or locale's defaults.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### currency
3-letter currency code as defined by ISO 4217, eg. `"USD"`.
#### options.style
Optional. String `"symbol"` (default), `"accounting"`, `"code"` or `"name"`. See [`.numberFormatter( [options] )`](../number/number-formatter.md) for more options.
#### value
Number to be formatted, eg. `9.99`.
### Example
#### Static Formatter
Prior to using any currency methods, you must load `cldr/main/{locale}/currencies.json`, `cldr/supplemental/currencyData.json`, and the CLDR content required by the number module. If using plural messages, you also must load the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Using the default options
You can use the static method `Globalize.currencyFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyFormatter( "USD" );
formatter( 9.99 );
// > "$9.99"
```
#### Instance Formatter
You can use the instance method `.currencyFormatter()`, which uses the instance locale.
```javascript
var deFormatter = Globalize( "de" ).currencyFormatter( "EUR" ),
zhFormatter = Globalize( "zh" ).currencyFormatter( "EUR" );
deFormatter( 9.99 );
// > "9,99 €"
zhFormatter( 9.99 );
// > "€ 9.99"
```
For comparison, follow the formatting output of different symbols in different locales.
| 3-letter currency code | en (English) | de (German) | zh (Chinese) |
| ---------------------------------- | ------------ | ----------- | ------------ |
| `.currencyFormatter( "USD" )( 1 )` | `$1.00` | `1,00 $` | `US$ 1.00` |
| `.currencyFormatter( "EUR" )( 1 )` | `€1.00` | `1,00 €` | `€ 1.00` |
| `.currencyFormatter( "CNY" )( 1 )` | `CN¥1.00` | `1,00 CN¥` | `¥ 1.00` |
| `.currencyFormatter( "JPY" )( 1 )` | `¥1` | `1 ¥` | `JP¥ 1` |
| `.currencyFormatter( "GBP" )( 1 )` | `£1.00` | `1,00 £` |  1.00` |
| `.currencyFormatter( "BRL" )( 1 )` | `R$1.00` | `1,00 R$` | `R$ 1.00` |
#### Using alternative `options.symbolForm`
Using the narrow symbol form, the same symbols may be used for multiple currencies. Thus the symbol may be ambiguous, and should only be used where the context is clear.
```js
Globalize( "en" ).currencyFormatter( "HKD" )( 1 );
// > "HK$1.00"
Globalize( "en" ).currencyFormatter( "HKD", { symbolForm: "narrow" } )( 1 );
// > "$1.00"
```
#### Configuring style
For the accounting variation of the symbol format, use `style: "accounting"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "accounting"
});
formatter( -1 );
// > "($1.00)"
```
For plural messages, use `style: "name"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "name"
});
formatter( 0 );
// > "0.00 US dollars"
formatter( 1 );
// > "1.00 US dollar"
```
For comparison, follow the formatting output of different symbols in different locales using the plural messages `Globalize( locale ).currencyFormatter( currency, { style: "name" } )( 1 )`.
| 3-letter currency code | en (English) | de (German) | zh (Chinese) |
| ---------------------- | ----------------------------- | -------------------------------- | ------------ |
| `USD` | `1.00 US dollar` | `1,00 US-Dollar` | `1.00美元` |
| `EUR` | `1.00 euro` | `1,00 Euro` | `1.00欧元` |
| `CNY` | `1.00 Chinese yuan` | `1,00 Chinesischer Yuan` | `1.00人民币` |
| `JPY` | `1 Japanese yen` | `1 Japanischer Yen` | `1日元` |
| `GBP` | `1.00 British pound sterling` | `1,00 Britisches Pfund Sterling` | `1.00英镑` |
| `BRL` | `1.00 Brazilian real` | `1,00 Brasilianischer Real` | `1.00巴西雷亚尔` |
For the international currency code, use `style: "code"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "code"
});
formatter( 9.99 );
// > "9.99 USD"
```
#### Configuring inherited number options
Override the number of digits, grouping separators, rounding function or any other [`.numberFormatter()` options](../number/number-formatter.md).
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyFormatter( "USD", {
minimumFractionDigits: 0,
style: "name"
});
formatter( 1 );
// > "1 US dollar"
formatter = Globalize.currencyFormatter( "USD", {
round: "ceil"
});
formatter( 1.491 );
// > "$1.50"
```
#### Formatting Compact Currencies
```js
var shortFormatter = Globalize( "en" ).currencyFormatter( "USD", {
compact: "short"
});
var longFormatter = Globalize( "en" ).currencyFormatter( "USD", {
compact: "long"
});
shortFormatter( 12830000000 );
// > "$13B"
longFormatter( 12830000000 );
// > "$13 billion"
```
The minimumSignificantDigits and maximumSignificantDigits options are specially useful to control the number of digits to display.
```js
Globalize( "en" ).formatCurrency( 12830000000, "USD", {
compact: "short",
minimumSignificantDigits: 3,
maximumSignificantDigits: 3
});
// > "$12.8B"
```
#### Performance Suggestion
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD" );
renderInvoice({
prices: prices.map(function( price ) {
return formatter( price );
})
});
```

View File

@@ -0,0 +1,117 @@
## .currencyToPartsFormatter( currency [, options] ) ➜ function( value )
Return a function that formats a `currency` into parts tokens according to the given `options` or locale's defaults.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### currency
3-letter currency code as defined by ISO 4217, eg. `"USD"`.
#### options
Please, see [.currencyFormatter() options](./currency-formatter.md#parameters).
#### value
Number to be formatted, eg. `9.99`.
### Returns
An Array of objects containing the formatted currency in parts. The returned structure looks like this:
```js
[
{ type: "day", value: "17" },
{ type: "weekday", value: "Monday" }
]
```
Possible types are the following:
- `currency`
The currency string, such as the symbols `"$"` and `"€"` or the name `"Dollar"`, `"Euro"` depending on which style is used.
Please, see [.numberToPartsFormatter()](../number/number-to-parts-formatter.md#returns) for details about the inherited number parts such as `decimal`, `fraction`, `group`, `infinity`, `integer`, `literal`, `minusSign`, `nan`, `plusSign`, `percentSign`, and `compact`.
### Example
Prior to using any currency methods, you must load `cldr/main/{locale}/currencies.json`, `cldr/supplemental/currencyData.json`, and the CLDR content required by the number module. If using plural messages, you also must load the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Static Formatter
#### Using the default options
You can use the static method `Globalize.currencyToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyToPartsFormatter( "USD" );
formatter( 9.99 );
// > [
// { "type": "currency", "value": "$" },
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "99" }
// ]
```
#### Instance Formatter
You can use the instance method `.currencyFormatter()`, which uses the instance locale.
```javascript
var deFormatter = Globalize( "de" ).currencyToPartsFormatter( "EUR" ),
zhFormatter = Globalize( "zh" ).currencyToPartsFormatter( "EUR" );
deFormatter( 9.99 );
// > [
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "," },
// { "type": "fraction", "value": "99" },
// { "type": "literal", "value": " " },
// { "type": "currency", "value": "€" }
// ]
zhFormatter( 9.99 );
// > [
// { "type": "currency", "value": "€" },
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "99" }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
#### More Examples
Please, see [.currencyFormatter() example](./currency-formatter.md#example) for additional examples such as using alternative `symbolForm`, configuring `style` (symbol, accounting, and name styles), and the inherited number options (e.g., compact numbers).
#### Performance Suggestion
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
var formatter = Globalize( "en" ).currencyToPartsFormatter( "USD" );
renderInvoice({
prices: prices.map(function( price ) {
return formatter( price );
})
});
```

View File

@@ -0,0 +1,203 @@
## .dateFormatter( [options] ) ➜ function( value )
Return a function that formats a date according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
The returned function is invoked with one argument: the Date instance `value` to be formatted.
### Parameters
#### options.skeleton
String value indicating a skeleton (see description above), eg. `{ skeleton: "GyMMMd" }`.
Skeleton provides a more flexible formatting mechanism than the predefined list `full`, `long`, `medium`, or `short` represented by date, time, or datetime. Instead, they are an open-ended list of patterns containing only date field information, and in a canonical order. For a complete list of skeleton patterns [check the unicode CLDR documentation](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table).
For example:
| locale | `"GyMMMd"` skeleton |
| ------ | ------------------------- |
| *en* | `"Apr 9, 2014 AD"` |
| *zh* | `"公元2014年4月9日"` |
| *es* | `"9 abr. de 2014 d. C."` |
| *ar* | `"٩ أبريل، ٢٠١٤ م"` |
| *pt* | `"9 de abr de 2014 d.C."` |
#### options.date
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ date: "full" }`.
#### options.time
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ time: "full" }`.
#### options.datetime
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ datetime: "full" }`.
#### options.raw
String value indicating a machine [raw pattern (anything in the "Sym." column)](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table) eg. `{ raw: "dd/mm" }`. Note this is NOT recommended for i18n in general. Use `skeleton` instead.
#### options.timeZone
String based on the time zone names of the [IANA time zone database](https://www.iana.org/time-zones), such as `"Asia/Shanghai"`, `"Asia/Kolkata"`, `"America/New_York"`.
#### value
Date instance to be formatted, eg. `new Date()`;
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/metaZones.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateFormatter();
formatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "11/30/2010"
```
You can use the instance method `.dateFormatter()`, which uses the instance locale.
```javascript
var enFormatter = Globalize( "en" ).dateFormatter(),
deFormatter = Globalize( "de" ).dateFormatter();
enFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "11/30/2010"
deFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "30.11.2010"
```
#### Using short, medium, long, and full presets
Use convenient presets for `date`, `time`, or `datetime`. Their possible values are: `short`, `medium`, `long`, and `full`.
| `presetValue` | `Globalize( "en" ).dateFormatter( presetValue )( new Date( 2010, 10, 1, 17, 55 ) )` |
| ------------------------ | ---------------------------------------- |
| `{ date: "short" }` | `"11/1/10"` |
| `{ date: "medium" }` | `"Nov 1, 2010"` |
| `{ date: "long" }` | `"November 1, 2010"` |
| `{ date: "full" }` | `"Monday, November 1, 2010"` |
| `{ time: "short" }` | `"5:55 PM"` |
| `{ time: "medium" }` | `"5:55:00 PM"` |
| `{ time: "long" }` | `"5:55:00 PM PST"` |
| `{ time: "full" }` | `"5:55:00 PM Pacific Standard Time"` |
| `{ datetime: "short" }` | `"11/1/10, 5:55 PM"` |
| `{ datetime: "medium" }` | `"Nov 1, 2010, 5:55:00 PM"` |
| `{ datetime: "long" }` | `"November 1, 2010 at 5:55:00 PM PST"` |
| `{ datetime: "full" }` | `"Monday, November 1, 2010 at 5:55:00 PM Pacific Standard Time"` |
For comparison, follow the same formatter `{ datetime: "short" }` on different locales.
| locale | `Globalize( locale ).dateFormatter({ datetime: "short" })( new Date( 2010, 10, 1, 17, 55 ) )` |
| ---------------- | ---------------------------------------- |
| *en* | `"11/1/10, 5:55 PM"` |
| *en_GB* | `"01/11/2010 17:55"` |
| *zh* | `"10/11/1 下午5:55"` |
| *zh-u-nu-native* | `"一〇/一一/一 下午五:五五"` |
| *es* | `"1/11/10 17:55"` |
| *de* | `"01.11.10 17:55"` |
| *pt* | `"01/11/10 17:55"` |
| *ar* | `"١/١١/٢٠١٠ ٥،٥٥ م"` |
#### Using open-ended skeletons
Use open-ended skeletons for more flexibility (see its description [above](#parameters)). See some examples below.
| `skeleton` | `Globalize( "en" ).dateFormatter( skeleton )( new Date( 2010, 10, 1, 17, 55 ) )` |
| ---------------------------- | ---------------------------------------- |
| `{ skeleton: "E" }` | `"Tue"` |
| `{ skeleton: "EHm" }` | `"Tue 17:55"` |
| `{ skeleton: "EHms" }` | `"Tue 17:55:00"` |
| `{ skeleton: "Ed" }` | `"30 Tue"` |
| `{ skeleton: "Ehm" }` | `"Tue 5:55 PM"` |
| `{ skeleton: "Ehms" }` | `"Tue 5:55:00 PM"` |
| `{ skeleton: "Gy" }` | `"2010 AD"` |
| `{ skeleton: "GyMMM" }` | `"Nov 2010 AD"` |
| `{ skeleton: "GyMMMEd" }` | `"Tue, Nov 30, 2010 AD"` |
| `{ skeleton: "GyMMMd" }` | `"Nov 30, 2010 AD"` |
| `{ skeleton: "H" }` | `"17"` |
| `{ skeleton: "Hm" }` | `"17:55"` |
| `{ skeleton: "Hms" }` | `"17:55:00"` |
| `{ skeleton: "M" }` | `"11"` |
| `{ skeleton: "MEd" }` | `"Tue, 11/30"` |
| `{ skeleton: "MMM" }` | `"Nov"` |
| `{ skeleton: "MMMEd" }` | `"Tue, Nov 30"` |
| `{ skeleton: "MMMd" }` | `"Nov 30"` |
| `{ skeleton: "Md" }` | `"11/30"` |
| `{ skeleton: "d" }` | `"30"` |
| `{ skeleton: "h" }` | `"5 PM"` |
| `{ skeleton: "hm" }` | `"5:55 PM"` |
| `{ skeleton: "hms" }` | `"5:55:00 PM"` |
| `{ skeleton: "ms" }` | `"55:00"` |
| `{ skeleton: "y" }` | `"2010"` |
| `{ skeleton: "yM" }` | `"11/2010"` |
| `{ skeleton: "yMEd" }` | `"Tue, 11/30/2010"` |
| `{ skeleton: "yMMM" }` | `"Nov 2010"` |
| `{ skeleton: "yMMMEd" }` | `"Tue, Nov 30, 2010"` |
| `{ skeleton: "yMMMd" }` | `"Nov 30, 2010"` |
| `{ skeleton: "yMd" }` | `"11/30/2010"` |
| `{ skeleton: "yQQQ" }` | `"Q4 2010"` |
| `{ skeleton: "yQQQQ" }` | `"4th quarter 2010"` |
| `{ skeleton: "GyMMMEdhms" }` | `"Tue, Nov 30, 2010 AD, 5:55:00 PM"` |
| `{ skeleton: "Ehms" }` | `"Tue 5:55:00 PM"` |
| `{ skeleton: "yQQQHm" }` | `"Q4 2010, 17:55"` |
| `{ skeleton: "MMMEdhm" }` | `"Tue, Nov 30, 5:55 PM"` |
| `{ skeleton: "yMMMdhm" }` | `"Nov 30, 2010, 5:55 PM"` |
```javascript
var globalize = Globalize( "en" ),
date = new Date( 2010, 10, 30, 17, 55 ),
monthDayFormatter = globalize.dateFormatter({ skeleton: "MMMd" }),
hourMinuteSecondFormatter = globalize.dateFormatter({ skeleton: "Hms" });
monthDayFormatter( date );
// > "Nov 30"
hourMinuteSecondFormatter( date );
// > "17:55:00"
```
#### Using time zones
Using specific timeZones, i.e., using `options.timezone`. Note that prior to using it, you must load IANA time zone data.
```js
Globalize.loadTimeZone( require( "iana-tz-data" ) );
```
```js
Globalize.locale( "en" );
Globalize.dateFormatter({ datetime: "medium", timeZone: "America/Los_Angeles" })( new Date() );
// > "Nov 1, 2010, 12:55:00 PM"
Globalize.dateFormatter({ datetime: "medium", timeZone: "America/Sao_Paulo" })( new Date() )
// > "Nov 1, 2010, 5:55:00 PM"
Globalize.dateFormatter({ datetime: "full", timeZone: "Europe/Berlin" })( new Date() )
// > "Monday, November 1, 2010 at 8:55:00 PM Central European Standard Time"
```
#### Note on performance
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
// In an application, this array could have a few hundred entries
var dates = [ new Date( 2010, 10, 30, 17, 55 ), new Date( 2015, 3, 18, 4, 25 ) ];
var formatter = Globalize( "en" ).dateFormatter({ time: "short" });
var formattedDates = dates.map(function( date ) {
return formatter( date );
});
// > Array [ "5:55 PM", "4:25 AM" ]
```

View File

@@ -0,0 +1,60 @@
## .dateParser( [options] ) ➜ function( value )
Return a function that parses a string representing a date into a JavaScript Date object according to the given `options`. The default parsing assumes numeric year, month, and day (i.e., `{ skeleton: "yMd" }`).
The returned function is invoked with one argument: the String `value` to be parsed.
### Parameters
#### options
See [.dateFormatter() options](./date-formatter.md#parameters).
#### value
String with date to be parsed, eg. `"11/1/10, 5:55 PM"`.
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.dateParser()`, which uses the default locale.
```javascript
var parser;
Globalize.locale( "en" );
parser = Globalize.dateParser();
parser( "1/2/2013" );
// > Wed Jan 02 2013 00:00:00
Globalize.locale( "es" );
parser = Globalize.dateParser();
parser( "1/2/2013" );
// > Fri Feb 01 2013 00:00:00
```
You can use the instance method `.dateParser()`, which uses the instance locale.
```javascript
var esParser = Globalize( "es" ).dateParser({ date: short });
esParser( "1/2/13" );
// > Fri Feb 01 2013 00:00:00
```
For improved performance on iterations, first create the parser. Then, reuse it
on each loop.
```javascript
var formattedDates = [ new Date( a ), new Date( b ), ... ];
var parser = Globalize( "en" ).dateParser({ time: "short" });
dates = formattedDates.map(function( formattedDate ) {
return parser( formattedDate );
});
```

View File

@@ -0,0 +1,176 @@
## .dateToPartsFormatter( [options] ) ➜ function( value )
Return a function that formats a date into parts tokens according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
The returned function is invoked with one argument: the Date instance `value` to be formatted.
### Parameters
#### options
Please, see [.dateFormatter() options](./date-formatter.md#parameters).
#### value
Date instance to be formatted, eg. `new Date()`;
### Returns
An Array of objects containing the formatted date in parts. The returned structure looks like this:
```js
[
{ type: "day", value: "17" },
{ type: "weekday", value: "Monday" }
]
```
Possible types are the following:
- `day`
The string used for the day, e.g., `"17"`, `"١٦"`.
- `dayperiod`
The string used for the day period, e.g., `"AM"`, `"PM"`.
- `era`
The string used for the era, e.g., `"AD"`, `"d. C."`.
- `hour`
The string used for the hour, e.g., `"3"`, `"03"`.
- `literal`
The string used for separating date and time values, e.g., `"/"`, `", "`,
`"o'clock"`, `" de "`.
- `minute`
The string used for the minute, e.g., `"00"`.
- `month`
The string used for the month, e.g., `"12"`.
- `second`
The string used for the second, e.g., `"07"` or `"42"`.
- `zone`
The string used for the name of the time zone, e.g., `"EST".`
- `weekday`
The string used for the weekday, e.g., `"M"`, `"Monday"`, `"Montag".`
- `year`
The string used for the year, e.g., `"2012"`, `"96".`
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.dateToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter();
formatter( new Date( 2010, 10, 30 ) );
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
```
You can use the instance method `.dateToPartsFormatter()`, which uses the instance locale.
```javascript
var enFormatter = Globalize( "en" ).dateToPartsFormatter(),
deFormatter = Globalize( "de" ).dateToPartsFormatter();
enFormatter( new Date( 2010, 10, 30 ) );
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
deFormatter( new Date( 2010, 10, 30 ) );
// > [
// { type: 'day', value: '30' },
// { type: 'literal', value: '.' },
// { type: 'month', value: '11' },
// { type: 'literal', value: '.' },
// { type: 'year', value: '2010' }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter({datetime: "short"});
formatter( new Date( 2010, 10, 30, 17, 55 ) ).map(({type, value}) => {
switch ( type ) {
case "year": return `<strong>${value}</strong>`;
default: return value;
}
}).join( "" );
// > "11/30/<strong>10</strong>, 5:55 PM"
```
Please, see [.dateFormatter() example](./date-formatter.md#example) for additional examples such as using `date`, `time`, `datetime`, and `skeleton` options.
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
// In an application, this array could have a few hundred entries
var dates = [ new Date( 2010, 10, 30, 17, 55 ), new Date( 2015, 3, 18, 4, 25 ) ];
var formatter = Globalize( "en" ).dateToPartsFormatter({ time: "short" });
var formattedDates = dates.map(function( date ) {
return formatter( date );
});
// > [
// [
// { "type": "hour", "value": "5" },
// { "type": "literal", "value": ":" },
// { "type": "minute", "value": "55" },
// { "type": "literal", "value": " " },
// { "type": "dayperiod", "value": "PM" }
// ],
// [
// { "type": "hour", "value": "4" },
// { "type": "literal", "value": ":" },
// { "type": "minute", "value": "25" },
// { "type": "literal", "value": " " },
// { "type": "dayperiod", "value": "AM" }
// ]
// ]
```

View File

@@ -0,0 +1,29 @@
## Globalize.loadTimeZone( ianaTzData )
This method allows you to load IANA time zone data to enable `options.timeZone` feature on date formatters and parsers.
### Parameters
#### ianaTzData
A JSON object with zdumped IANA timezone data. Get the data via [`iana-tz-data`](https://github.com/rxaviers/iana-tz-data).
### Example
```javascript
Globalize.loadTimeZone({
"zoneData": {
...
"America": {
...
"New_York": {
abbrs: [],
untils: [],
offsets: [],
isdsts: []
}
...
}
}
});
```

View File

@@ -0,0 +1,105 @@
## .loadMessages( json )
Load messages data.
The first level of keys must be locales. For example:
```
{
en: {
hello: "Hello"
},
pt: {
hello: "Olá"
}
}
```
ICU MessageFormat pattern is supported: variable replacement, gender and plural inflections. For more information see [`.messageFormatter( path ) ➡ function([ variables ])`](./message-formatter.md).
The provided messages are stored along side other cldr data, under the "globalize-messages" key. This allows Globalize to reuse the traversal methods provided by cldrjs. You can inspect this data using `cldrjs.get("globalize-messages")`.
### Parameters
#### json
JSON object of messages data. Keys can use any character, except `/`, `{` and `}`. Values (i.e., the message content itself) can contain any character.
### Example
```javascript
Globalize.loadMessages({
pt: {
greetings: {
hello: "Olá",
bye: "Tchau"
}
}
});
Globalize( "pt" ).formatMessage( "greetings/hello" );
// > Olá
```
#### Multiline strings
Use Arrays as a convenience for multiline strings. The lines will be joined by a space.
```javascript
Globalize.loadMessages({
en: {
longText: [
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi non",
"quis exercitationem culpa nesciunt nihil aut nostrum explicabo",
"reprehenderit optio amet ab temporibus asperiores quasi cupiditate.",
"Voluptatum ducimus voluptates voluptas?"
]
}
});
Globalize( "en" ).formatMessage( "longText" );
// > "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi non quis exercitationem culpa nesciunt nihil aut nostrum explicabo reprehenderit optio amet ab temporibus asperiores quasi cupiditate. Voluptatum ducimus voluptates voluptas?"
```
#### Messages inheritance
It's possible to inherit messages, for example:
```javascript
Globalize.loadMessages({
root: {
amen: "Amen"
},
de: {},
en: {},
"en-GB": {},
fr: {},
pt: {
amen: "Amém"
},
"pt-PT": {}
});
Globalize( "de" ).formatMessage( "amen" );
// > "Amen"
Globalize( "en" ).formatMessage( "amen" );
// > "Amen"
Globalize( "en-GB" ).formatMessage( "amen" );
// > "Amen"
Globalize( "fr" ).formatMessage( "amen" );
// > "Amen"
Globalize( "pt-PT" ).formatMessage( "amen" );
// > "Amém"
```
Note that `de`, `en`, `en-GB`, `fr`, and `pt-PT` are empty. `.formatMessage()` inherits `pt-PT` messages from `pt` (`pt-PT``pt`), and it inherits the other messages from root, eg. `en-GB``en-001``en``root`. Yes, `root` is the last bundle of the parent lookup.
Attention: On browsers, message inheritance only works if the optional dependency `cldr/unresolved` is loaded.
```html
<script src="cldr/unresolved.js"></script>
```

View File

@@ -0,0 +1,208 @@
## .messageFormatter( path ) ➡ function([ variables ])
Return a function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections.
Use [`Globalize.loadMessages( json )`](./load-messages.md) to load
messages data.
### Parameters
#### path
String or Array containing the path of the message content, eg., `"greetings/bye"`, or `[ "greetings", "bye" ]`.
#### variables
Optional. Variables can be Objects, where each property can be referenced by name inside a message; or Arrays, where each entry of the Array can be used inside a message, using numeric indices. When passing one or more arguments of other types, they're converted to an Array and used as such.
### Example
You can use the static method `Globalize.messageFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.loadMessages({
pt: {
greetings: {
bye: "Tchau"
}
}
});
Globalize.locale( "pt" );
formatter = Globalize.messageFormatter( "greetings/bye" );
formatter();
// > "Tchau"
```
You can use the instance method `.messageFormatter()`, which uses the instance locale.
```javascript
var pt = new Globalize( "pt" ),
formatter = pt.messageFormatter( "greetings/bye" );
formatter();
// > "Tchau"
```
#### Simple Variable Replacement
```javascript
var formatter;
Globalize.loadMessages({
en: {
hello: "Hello, {0} {1} {2}",
hey: "Hey, {first} {middle} {last}"
}
});
formatter = Globalize( "en" ).messageFormatter( "hello" );
// Numbered variables using Array.
formatter([ "Wolfgang", "Amadeus", "Mozart" ]);
// > "Hello, Wolfgang Amadeus Mozart"
// Numbered variables using function arguments.
formatter( "Wolfgang", "Amadeus", "Mozart" );
// > "Hello, Wolfgang Amadeus Mozart"
// Named variables using Object key-value pairs.
formatter = Globalize( "en" ).messageFormatter( "hey" );
formatter({
first: "Wolfgang",
middle: "Amadeus",
last: "Mozart"
});
// > "Hey, Wolfgang Amadeus Mozart"
```
#### Gender inflections
`select` can be used to format any message variations that works like a switch.
```javascript
var formatter;
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
party: [
"{hostGender, select,",
" female {{host} invites {guest} to her party}",
" male {{host} invites {guest} to his party}",
" other {{host} invites {guest} to their party}",
"}"
]
}
});
formatter = Globalize( "en" ).messageFormatter( "party" );
formatter({
guest: "Mozart",
host: "Beethoven",
hostGender: "male"
});
// > "Beethoven invites Mozart to his party"
```
#### Plural inflections
It uses the plural forms `zero`, `one`, `two`, `few`, `many`, or `other` (required). Note English only uses `one` and `other`. So, including `zero` will never get called, even when the number is 0. For more information see [`.pluralGenerator()`](../plural/plural-generator.md).
```javascript
var numberFormatter, taskFormatter,
en = new Globalize( "en" );
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
task: [
"You have {count, plural,",
" one {one task}",
" other {{formattedCount} tasks}",
"} remaining"
]
}
});
numberFormatter = en.numberFormatter();
taskFormatter = en.messageFormatter( "task" );
taskFormatter({
count: 1000,
formattedCount: numberFormatter( 1000 )
});
// > "You have 1,000 tasks remaining"
```
Literal numeric keys can be used in `plural` to match single, specific numbers.
```javascript
var taskFormatter,
en = new Globalize( "en" );
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
task: [
"You have {count, plural,",
" =0 {no tasks}",
" one {one task}",
" other {{formattedCount} tasks}",
"} remaining"
]
}
});
taskFormatter = Globalize( "en" ).messageFormatter( "task" );
taskFormatter({
count: 0,
formattedCount: en.numberFormatter( 0 )
});
// > "You have no tasks remaining"
```
You may find useful having the plural forms calculated with an offset applied.
Use `#` to output the resulting number. Note literal numeric keys do NOT use the
offset value.
```javascript
var likeFormatter,
en = new Globalize( "en" );
Globalize.loadMessages({
en: {
likeIncludingMe: [
"{0, plural, offset:1",
" =0 {Be the first to like this}",
" =1 {You liked this}",
" one {You and someone else liked this}",
" other {You and # others liked this}",
"}"
]
}
});
likeFormatter = Globalize( "en" ).messageFormatter( "likeIncludingMe" );
likeFormatter( 0 );
// > "Be the first to like this"
likeFormatter( 1 );
// > "You liked this"
likeFormatter( 2 );
// > "You and someone else liked this"
likeFormatter( 3 );
// > "You and 2 others liked this"
```
Read on [SlexAxton/messageFormatter.js][] for more information on regard of ICU MessageFormat.
[SlexAxton/messageFormatter.js]: https://github.com/SlexAxton/messageformat.js/#no-frills

View File

@@ -0,0 +1,202 @@
## .numberFormatter( [options] ) ➜ function( value )
Return a function that formats a number according to the given options.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### options.style
Optional. String `decimal` (default), or `percent`.
#### options.minimumIntegerDigits
Optional. Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary.
#### options.minimumFractionDigits, options.maximumFractionDigits
Optional. Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns.
#### options.minimumSignificantDigits, options.maximumSignificantDigits
Optional. Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits.
#### options.round
Optional. String with rounding method `ceil`, `floor`, `round` (default), or `truncate`.
#### options.useGrouping
Optional. Boolean (default is true) value indicating whether a grouping separator should be used.
#### options.compact
Optional. String `short` or `long` indicating which compact number format should be used to represent the number.
### Examples
#### Static Formatter
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.numberFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.numberFormatter();
formatter( 3.141592 );
// > "3.142"
```
#### Instance Formatter
You can use the instance method `.numberFormatter()`, which uses the instance
locale.
```javascript
var arFormatter = Globalize( "ar" ).numberFormatter(),
esFormatter = Globalize( "es" ).numberFormatter(),
zhFormatter = Globalize( "zh-u-nu-native" ).numberFormatter();
arFormatter( 3.141592 );
// > "٣٫١٤٢"
esFormatter( 3.141592 );
// > "3,142"
zhFormatter( 3.141592 );
// > "三.一四二"
```
#### Configuring decimal places
The number of decimal places can be decreased or increased using `minimumFractionDigits` and `maximumFractionDigits`.
```javascript
Globalize.numberFormatter({ maximumFractionDigits: 2 })( 3.141592 );
// > "3.14"
Globalize.numberFormatter({ minimumFractionDigits: 2 })( 1.5 );
// > "1.50"
```
#### Configuring significant digits
The number of significant (non-zero) digits can be decreased or increased using `minimumSignificantDigits` and `maximumSignificantDigits`.
```javascript
var formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 3.141592 );
// > "3.14"
formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 12345 );
// > "12,300"
formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 0.00012345 );
// > "0.000123"
```
#### Formatting Percentages
Numbers can be formatted as percentages.
```javascript
var enFormatter = Globalize( "en" ).numberFormatter({
style: "percent",
minimumFractionDigits: 1,
maximumFractionDigits: 1
});
var frFormatter = Globalize( "fr" ).numberFormatter({
style: "percent",
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
enFormatter( 0.0016 );
// > "0.2%"
enFormatter( 0.0014 );
// > "0.1%"
frFormatter( 0.0005 );
// > "0,05 %"
```
#### Formatting Compact Numbers
Long numbers can be represented in a compact format, with `short` using abbreviated units and `long` using the full unit name.
```javascript
var shortFormatter = Globalize( "en" ).numberFormatter({
compact: "short"
});
var longFormatter = Globalize( "en" ).numberFormatter({
compact: "long"
});
shortFormatter( 27588910 );
// > "28M"
longFormatter( 27588910 );
// > "28 million"
```
The minimumSignificantDigits and maximumSignificantDigits options are specially useful to control the number of digits to display.
```js
Globalize( "en" ).formatNumber( 27588910, {
compact: "short",
minimumSignificantDigits: 3,
maximumSignificantDigits: 3
});
// > "27.6M"
```
#### Configuring Rounding
Numbers with a decreased amount of decimal places can be rounded up, rounded down, rounded arithmetically, or truncated by setting the `round` option to `ceil`, `floor`, `round` (default), or `truncate`.
```javascript
var formatter = Globalize.numberFormatter({
maximumFractionDigits: 2,
round: "ceil"
});
formatter( 3.141592 );
// > "3.15"
```
#### Performance Suggestions
For improved performance on iterations, the formatter should be created before the loop. Then, it can be reused in each iteration.
```javascript
var numbers = [ 1, 1, 2, 3, ... ];
var formatter = Globalize( "en" ).numberFormatter();
formattedNumbers = numbers.map(function( number ) {
return formatter( number );
});
```

View File

@@ -0,0 +1,130 @@
## .numberParser( [options] ) ➜ function( value )
Return a function that parses a String representing a number according to the given options. If value is invalid, `NaN` is returned.
The returned function is invoked with one argument: the String representing a number `value` to be parsed.
### Parameters
#### options
See [.numberFormatter() options](./number-formatter.md#parameters).
#### value
String with number to be parsed, eg. `"3.14"`.
### Example
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.numberParser()`, which uses the default locale.
```javascript
var parser;
Globalize.locale( "en" );
parser = Globalize.numberParser();
parser( "3.14" );
// > 3.14
```
You can use the instance method `.numberParser()`, which uses the instance locale.
```javascript
var enParser = Globalize( "en" ).numberParser(),
esParser = Globalize( "es" ).numberParser();
enParser( "3.14" );
// > 3.14
esParser( "3,14" );
// > 3.14
```
Some more examples.
```javascript
var enParser = Globalize( "en" ).numberParser();
enParser( "12,735" );
// > 12735
enParser( "12,735.00" );
// > 12735
Globalize( "en" ).numberParser({ style: "percent" })( "100%" );
// > 1
enParser( "∞" );
// > Infinity
enParser( "-3" );
// > -3
enParser( "-∞" );
// > -Infinity
enParser( "invalid-stuff" );
// > NaN
enParser( "invalid-stuff-that-includes-number-123" );
// > NaN
enParser( "invalid-stuff-123-that-includes-number" );
// > NaN
enParser( "123-invalid-stuff-that-includes-number" );
// > NaN
// Invalid decimal separator. (note `.` is used as decimal separator for English)
enParser( "3,14" );
// > NaN
// Invalid grouping separator position.
enParser( "127,35.00" );
// > NaN
```
Loose matching examples.
```js
var svParser = Globalize( "sv" ).numberParser();
// Swedish uses NO-BREAK-SPACE U+00A0 as grouping separator.
svParser( "1\xA0000,50" );
// > 1000.5
// The parser is lenient and accepts various space characters like regular space
// SPACE U+0020. Technically, it accepts any character of the Unicode general
// category [:Zs:].
svParser( "1 000,50" );
// > 1000.5
var fiParser = Globalize( "fi" ).numberParser();
// Finish uses MINUS SIGN U+2212 for the minus sign.
fiParser( "\u22123" );
// > -3
// The parser is lenient and accepts various hyphen characters like regular
// HYPHEN-MINUS U+002D. Technically, it accepts any character of the Unicode
// general category [:Dash:].
fiParser( "-3" );
// > -3
```
For improved performance on iterations, first create the parser. Then, reuse it
on each loop.
```javascript
var formattedNumbers = [ "1", "1", "2", "3", ... ];
var parser = Globalize( "en" ).numberParser();
numbers = formattedNumbers.map(function( formattedNumber ) {
return parser( formattedNumber );
});
```

View File

@@ -0,0 +1,140 @@
## .numberToPartsFormatter( [options] ) ➜ function( value )
Return a function that formats a number into parts tokens according to the given options.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### options
Please, see [.numberFormatter() options](./number-formatter.md#parameters).
### Returns
An Array of objects containing the formatted number in parts. The returned structure looks like this:
- `decimal`
The decimal separator string, e.g., `"."`.
- `fraction`
The fraction number.
- `group`
The group separator string, e.g., `","`.
- `infinity`
The Infinity string, e.g., `"∞"`.
- `integer`
The integer number.
- `literal`
Any literal strings or whitespace in the formatted number.
- `minusSign`
The minus sign string, e.g., `"-"`.
- `nan`
The NaN string, e.g., `"NaN"`.
- `plusSign`
The plus sign string, e.g., `"+"`.
- `percentSign`
The percent sign string, e.g., `"%"`.
- `compact`
The compact string, e.g., `"thousand"`.
### Examples
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Static Formatter
You can use the static method `Globalize.numberToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.numberToPartsFormatter();
formatter( 3.141592 );
// > [
// { "type": "integer", "value": "3" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "142" }
// ]
```
#### Instance Formatter
You can use the instance method `.numberFormatter()`, which uses the instance
locale.
```javascript
var arFormatter = Globalize( "ar" ).numberToPartsFormatter(),
esFormatter = Globalize( "es" ).numberToPartsFormatter(),
zhFormatter = Globalize( "zh-u-nu-native" ).numberToPartsFormatter();
arFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "٣" },
// { "type": "decimal", "value": "٫" },
// { "type": "fraction", "value": "١٤٢" }
// ]
esFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "3" },
// { "type": "decimal", "value": "," },
// { "type": "fraction", "value": "142" }
// ]
zhFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "三" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "一四二" }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
#### More Examples
Please, see [.numberFormatter() example](./number-formatter.md#example) for additional examples such as configuring decimal places, significant digits, percentages, and compact numbers.
#### Performance Suggestions
For improved performance on iterations, the formatter should be created before the loop. Then, it can be reused in each iteration.
```javascript
var numbers = [ 1, 1, 2, 3, ... ];
var formatter = Globalize( "en" ).numberFormatter();
formattedNumbers = numbers.map(function( number ) {
return formatter( number );
});
```

View File

@@ -0,0 +1,84 @@
## .pluralGenerator( [options] ) ➜ function( value )
It supports the creation of internationalized messages with plural inflection by returning a function that returns the value's plural group: `zero`, `one`, `two`, `few`, `many`, or `other`.
The returned function is invoked with one argument: the Number `value` for which to return the plural group.
### Parameters
#### options.type
Optional. String `cardinal` (default), or `ordinal`.
#### value
A Number for which to return the plural group.
### Example
Prior to using any plural method, you must load either `supplemental/plurals.json` for cardinals or `supplemental/ordinals.json` for ordinals.
Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.pluralGenerator()`, which uses the default locale.
```javascript
var plural;
Globalize.locale( "en" );
// Cardinals
plural = Globalize.pluralGenerator();
plural( 0 );
// > "other"
plural( 1 );
// > "one"
plural( 2 );
// > "other"
// Ordinals
plural = Globalize.pluralGenerator({ type: "ordinal" });
plural( 0 );
// > "other"
plural( 1 );
// > "one"
plural( 2 );
// > "two"
```
You can use the instance method `.pluralGenerator()`, which uses the instance locale.
```javascript
var plural = Globalize( "zh" ).pluralGenerator();
plural( 1 );
// > "other"
```
For comparison (cardinals):
| | en (English) | ru (Russian) | ar (Arabic) |
| ------------- | ------------ | ------------ | ----------- |
| `plural( 0 )` | `other` | `many` | `zero` |
| `plural( 1 )` | `one` | `one` | `one` |
| `plural( 2 )` | `other` | `few` | `two` |
| `plural( 3 )` | `other` | `few` | `few` |
| `plural( 5 )` | `other` | `many` | `few` |
For comparison (ordinals):
| | en (English) | ru (Russian) | ar (Arabic) |
| ---------------------------------- | ------------ | ------------ | ----------- |
| `plural( 0, { type: "ordinal" } )` | `other` | `other` | `other` |
| `plural( 1, { type: "ordinal" } )` | `one` | `other` | `other` |
| `plural( 2, { type: "ordinal" } )` | `two` | `other` | `other` |
| `plural( 3, { type: "ordinal" } )` | `few` | `other` | `other` |
| `plural( 5, { type: "ordinal" } )` | `other` | `other` | `other` |

View File

@@ -0,0 +1,60 @@
## .relativeTimeFormatter( unit [, options] ) ➜ function( value )
Returns a function that formats a relative time according to the given unit, options, and the default/instance locale.
The returned function is invoked with one argument: the number `value` to be formatted.
### Parameters
#### unit
String value indicating the unit to be formatted. eg. "day", "week", "month", etc.
#### options.form
String, e.g., `"short"` or `"narrow"`, or falsy for default long form.
#### value
The number to be formatted.
### Example
Prior to using any relative time methods, you must load `cldr/main/{locale}/dateFields.json` and the CLDR content required by the number and plural modules. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.relativeTimeFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.relativeTimeFormatter( "month" );
formatter( 1 );
// > "next month"
formatter( 3 );
// > "in 3 months"
formatter( -1 );
// > "last month"
formatter( -3 );
// > "3 months ago"
```
You can use the instance method `.relativeTimeFormatter()`, which uses the instance locale.
```javascript
var globalize = new Globalize( "en" ),
formatter = globalize.relativeTimeFormatter( "week" );
formatter( 1 );
// > "next week"
```

View File

@@ -0,0 +1,72 @@
## .unitFormatter( unit [, options] ) ➜ function( value )
Returns a function that formats a unit according to the given unit, options, and the default/instance locale.
The returned function is invoked with one argument: the number `value` to be formatted.
### Parameters
#### unit
String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour"
#### options.form
Optional. String, e.g., `"long"` (default), `"short"` or `"narrow"`.
#### options.numberFormatter
Optional. A number formatter function. Defaults to `Globalize.numberFormatter()` for the current locale using the default options.
#### value
The number to be formatted.
### Example
Prior to using any unit methods, you must load `cldr/main/{locale}/units.json` and the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.unitFormatter()`, which uses the default locale.
```javascript
var customNumberFormatter, formatter;
Globalize.locale( "en" );
formatter = Globalize.unitFormatter( "month", { form: "long" } );
formatter( 1 );
// > "1 month"
formatter( 3 );
// > "3 months"
formatter( 3000 );
// > "3,000 months"
```
You can pass a custom number formatter to format the number of units.
```javascript
var customNumberFormatter, formatter;
Globalize.locale( "en" );
customNumberFormatter = Globalize.numberFormatter({ useGrouping = false })
formatter = Globalize.unitFormatter( "mile-per-hour", {
form: "narrow", numberFormatter: customNumberFormatter
} );
formatter(5000)
// > "5000mph"
```
You can use the instance method `.unitFormatter()`, which uses the instance locale.
```javascript
var globalize = new Globalize( "en" ),
formatter = globalize.unitFormatter( "mile-per-hour", { form: "narrow" } );
formatter( 10 );
// > "10mph"
```

View File

@@ -0,0 +1,177 @@
# Globalize 1.3.0 announcement
On July 3rd, we released Globalize 1.3.0. It is a special release, because it includes some very useful feature enhancements to support advanced date, time, timezone manipulation, and other long due fixes. We wanted to share more details on these improvements.
## IANA/Olson Time Zone Support
> This change was contributed by Kandaswamy Manikandan @rajavelmani (PayPal) and Rafael Xavier @rxaviers in #687 and #701.
In previous versions, Globalize had some partial time zone support for a user's runtime time zone. However specific CLDR patterns (`z`, `v`, and `V`) that display strings such as `PDT`, `Pacific Daylight Time`, `Pacific Time`, and `Los Angeles Time` could not be displayed. The challenge [we had](https://github.com/globalizejs/globalize/pull/202) to determine how costly a solution would be to provide full IANA/Olson time zone support due to the additional manipulation code and data (i.e., IANA database). Therefore, in the past, we encouraged users that needed to manipulate date in arbitrary time zones to use a separate library, like *moment-timezone*. Nevertheless, this solution never closed the gap between internationalization (i18n) implementations leveraging CLDR and having full maneuverability of time zones.
With the latest release 1.3.0, Globalize fully supports time zone. Simply put, by using Globalize 1.3.0, you now have full IANA support with the strength of CLDR for i18n!
```js
Globalize.locale("en");
let date = new Date();
Globalize.formatDate(date, {datetime: "short", timeZone: "America/Los_Angeles"});
// > '3/19/17, 3:19 PM'
Globalize.formatDate(date, {datetime: "short", timeZone: "America/New_York"});
// > '3/19/17, 6:19 PM'
Globalize.formatDate(date, {datetime: "short", timeZone: "America/Sao_Paulo"});
// > '3/19/17, 7:19 PM'
Globalize.formatDate(date, {datetime: "short", timeZone: "Europe/Berlin"});
// > '3/19/17, 11:19 PM'
Globalize.formatDate(date, {datetime: "full", timeZone: "America/Los_Angeles"});
// > 'Sunday, March 19, 2017 at 3:19:22 PM Pacific Daylight Time'
Globalize.formatDate(date, {datetime: "full", timeZone: "America/New_York"});
// > 'Sunday, March 19, 2017 at 6:19:22 PM Eastern Daylight Time'
Globalize.formatDate(date, {datetime: "full", timeZone: "America/Sao_Paulo"});
// > 'Sunday, March 19, 2017 at 7:19:22 PM Brasilia Standard Time'
Globalize.formatDate(date, {datetime: "full", timeZone: "Europe/Berlin"});
// > 'Sunday, March 19, 2017 at 11:19:22 PM Central European Standard Time'
Globalize("pt").formatDate(date, {datetime: "full", timeZone: "America/Sao_Paulo"});
// > 'domingo, 19 de março de 2017 19:19:22 Horário Padrão de Brasília'
Globalize("de").formatDate(date, {datetime: "full", timeZone: "Europe/Berlin"});
// > 'Sonntag, 19. März 2017 um 23:19:22 Mitteleuropäische Normalzeit'
Globalize("zh").formatDate(date, {datetime: "full", timeZone: "Asia/Shanghai"});
// > '2017年3月20日星期一 中国标准时间 上午6:19:22'
Globalize("ar").formatDate(date, {datetime: "full", timeZone: "Africa/Cairo"});
// > 'الاثنين، ٢٠ مارس، ٢٠١٧ ١٢:١٩:٢٢ ص توقيت شرق أوروبا الرسمي'
```
We have solved this in a low footprint, high performance implementation using [zoned-date-time](https://github.com/rxaviers/zoned-date-time) under the hoods, which is a 0.6KB library for the time zone manipulations. We have leveraged the Globalize Compiler for precompling the IANA data base for production. For example, let's say you are serving content in English (e.g. locale en-US) for America/Los_Angeles time using the following formatter:
```js
var dateWithTimeZoneFormatter = Globalize.dateFormatter({
datetime: "full",
timeZone: "America/Los_Angeles"
});
```
The final size (for production) of this code will be:
| filename | minified+gzipped size |
| ---------------------------------------- | --------------------- |
| i18n/en.js (includes CLDR and IANA data) | 1.7KB |
| core, number, and date globalize runtime lib + zoned-date-time | 7.0KB |
See globalize [compiler example](https://github.com/globalizejs/globalize/tree/master/examples/globalize-compiler) or [app-npm-webpack example](https://github.com/globalizejs/globalize/tree/master/examples/app-npm-webpack) for details.
## Format Date To Parts
> This change was contributed by Reza Payami @rpayami (PayPal) and Rafael Xavier @rxaviers in #697 and #700.
Modern user interfaces often need to manipulate the date format output, which is impossible via the existing format function that returns an opaque string. Making any attempt to do this can break internationalization support. [Ecma-402](https://github.com/tc39/ecma402/) has recently added [`Intl.DateTimeFormat.prototype.formatToParts`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts) to fulfill that purpose, which at the time of this post, is at stage 4 and is implemented by latest Firefox and Chrome.
In Globalize, we introduced [`.dateToPartsFormatter`](https://github.com/globalizejs/globalize/blob/master/doc/api/date/date-to-parts-formatter.md) and [`.formatDateToParts`](https://github.com/globalizejs/globalize/blob/master/doc/api/date/date-to-parts-formatter.md).
```js
Globalize.locale( "en" );
Globalize.formatDateToParts(new Date(2010, 10, 30));
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
```
The data is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), a [switch statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch), [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), and [`Array.prototype.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
```js
let formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter({datetime: "short"});
formatter( new Date( 2010, 10, 30, 17, 55 ) ).map(({type, value}) => {
switch ( type ) {
case "year": return `<strong>${value}</strong>`;
default: return value;
}
}).join( "" );
// > "11/30/<strong>10</strong>, 5:55 PM"
```
See [React Date Input](https://github.com/rxaviers/react-date-input) as a demo of a UI component for React optimized for i18n and a11y.
| Localized and smart date input | Feb 28 in `en`, `es`, `pt`, `de`, `zh`, `ko`, and `ar` |
| ---------------------------------------- | ---------------------------------------- |
| ![en](https://media.giphy.com/media/xUA7aZAUNINGP2jI4M/giphy.gif) | ![en-es-pt-de-zh-ko-ar](https://media.giphy.com/media/3og0ILQu0KxLRewJnW/giphy.gif) |
## Dynamically Augmented Date Skeletons
> This change was contributed by Marat Dyatko @vectart and Artur Eshenbrener @Strate in #462 and #604.
The style used to display a date format often varies depending on the application. CLDR offers data for certain presets like short (e.g., short date `"7/1/17"`), medium (e.g., medium date `"Jul 1, 2017"`), long (e.g., long date `"July 1, 2017"`), and full (e.g., full date `"Saturday, July 1, 2017"`). Although, we may want something different such as `"Jul 1"`. For that CLDR offers data for individual [date fields](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table) and their combinations, which are used by Globalize to synthesize an open-ended list of custom formats (called skeletons). But, what's interesting is that it would be prohibitively large if CLDR provided data for every single possible combination. So, there's an algorithm specified by [UTS#35](http://www.unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems) to deduce missing data from the requested format.
For the `"Jul 1"` example, we should use `{skeleton: "MMMd"}`. Internally, Globalize finds a direct match in CLDR for the requested skeleton. This works fine in previous Globalize versions.
For that next example, let's assume we want `"July 1"`, i.e., `{skeleton: "MMMMd"}`. Internally, Globalize doesn't find a direct match in CLDR. For this skeleton, Globalize needs to use the data for `MMMd`, which maps to `"MMM d"` in the English case, and then it needs to replace `MMM` with `MMMM` dynamically generating `"MMMM d"`. This doesn't work in previous versions of Globalize, but it works now on latest v1.3.0.
If we wanted `"07/01"` instead, we should use `{skeleton: "MMdd"}`. Internally, Globalize doesn't find a direct match in CLDR for this skeleton and, therefore, it fais in globalize v1.2.3. Globalize needs to use the data for `Md`, which in the case of English maps to `"M/d"`, and then replace `M` wtih `MM` and `d` with `dd` dynamically generating `"MM/dd"`.
To make a long story short, the algorithm in globalize v1.3.0 has been significantly improved and it allows using virtually any skeletons.
```js
// A skeleton not directly found in CLDR and that needs to be deduced by globalize.
// In English, globalize needs to use the data for GyMMMEd, and adjust MMM with MMMM,
// and E with EEEE. Then, it needs to find the data for hms and glue them together
// using the appropriate format.
// On globalize v1.2.3, an error is thrown saying this skeleton wasn't found.
let skeleton = "GyMMMMEEEEdhms";
Globalize("en").formatDate(new Date(), {skeleton});
// > 'Saturday, July 1, 2017 AD at 4:58:27 PM'
Globalize("pt").formatDate(new Date(), {skeleton});
// > 'sábado, 1 de julho de 2017 d.C. 5:01:20 PM'
Globalize("de").formatDate(new Date(), {skeleton});
// > 'Samstag, 1. Juli 2017 n. Chr. um 5:01:33 nachm.'
Globalize("zh").formatDate(new Date(), {skeleton});
// > '公元2017年七月月1日星期六 下午5:01:35'
Globalize("ko").formatDate(new Date(), {skeleton});
// > 'AD 2017년 7월 1일 토요일 오후 5:01:38'
Globalize("ar").formatDate(new Date(), {skeleton});
// > 'السبت، ١ يوليو، ٢٠١٧ م ٥:٠١:٤٠ م'
Globalize("ar-MA").formatDate(new Date(), {skeleton});
// > 'السبت، 1 يوليوز، 2017 م 5:04:29 م'
Globalize("it").formatDate(new Date(), {skeleton});
// > 'sabato 1 luglio 2017 d.C. 5:01:52 PM'
```
Read our [getting started](https://github.com/globalizejs/globalize/#getting-started) and play with it yourself.
## Other Enhancements and Bug Fixes
🎉 Enhancements
- Date: Show timezone offset optional minutes for O pattern (e.g., GMT-6:30 note the :30) [#339](https://github.com/globalizejs/globalize/pull/339) (via PR [#729](https://github.com/globalizejs/globalize/pull/729)) (Rafael Xavier)
- Date: Show timezone offset optional minutes and seconds for x and X patterns (e.g., -06:30 note the :30) [#339](https://github.com/globalizejs/globalize/pull/339) (via PR [#729](https://github.com/globalizejs/globalize/pull/729)) (Rafael Xavier)
- Date: Assert options.skeleton (PR [#726](https://github.com/globalizejs/globalize/pull/726)) (Rafael Xavier)
- Date parser: Make runtime phase lighter [#735](https://github.com/globalizejs/globalize/pull/735) (Rafael Xavier)
- Date parser: Loose Matching PR [#730](https://github.com/globalizejs/globalize/pull/730) (Rafael Xavier)
- Allows, among others, parsing arabic dates as user types them (i.e., without control characters)
- Number formatter: Amend integer and fraction formatter for small numbers like 1e-7 [#750](https://github.com/globalizejs/globalize/pull/750) (Rafael Xavier)
- Number parser: Lenient about trailing decimal separator [#744](https://github.com/globalizejs/globalize/pull/744) (Rafael Xavier)
- Runtime: Use strict [#676](https://github.com/globalizejs/globalize/pull/676) (Zack Birkenbuel)
🐛 Fixes
- Date parser: invalid output by mixing numbering systems [#696](https://github.com/globalizejs/globalize/pull/696) (via PR [#733](https://github.com/globalizejs/globalize/pull/733)) (Rafael Xavier)
- Date parser: fails on Turkish full datetime with Monday or Saturday [#690](https://github.com/globalizejs/globalize/pull/690) (via PR [#732](https://github.com/globalizejs/globalize/pull/732)) (Rafael Xavier)
⚙️ Others
- Compiler tests! [#721](https://github.com/globalizejs/globalize/pull/721) (via PR [#727](https://github.com/globalizejs/globalize/pull/727)) (Nikola Kovacs)
- Documentation style refactor [#737](https://github.com/globalizejs/globalize/pull/737) (Rafael Xavier)
## Last but not least
Special thanks to other PayPal internationalization team members including Daniel Bruhn, Lucas Welti, Alolita Sharma, Mike McKenna for testing and helping integrate Globalize for PayPal products.
Special thanks to James Bellenger and Nicolas Gallagher for the React and Webpack integration enhancements for Twitter products, which certainly deserves its own blog post.
Many thanks to all of you who participated in this release by testing, reporting bugs, or submitting patches, including Jörn Zaefferer, Frédéric Miserey, Nova Patch, and whole Globalize team.

View File

@@ -0,0 +1,114 @@
# Unicode CLDR usage
## How do I get CLDR data?
*By downloading the JSON packages individually...*
Unicode CLDR is available as JSON at https://github.com/unicode-cldr/ (after this [json-packaging proposal][] took place). Please, read https://github.com/unicode-cldr/cldr-json for more information about package organization.
[json-packaging proposal]: http://cldr.unicode.org/development/development-process/design-proposals/json-packaging
*By using a package manager...*
`cldr-data` can be used for convenience. It always downloads from the correct source.
Use bower `bower install cldr-data` ([detailed instructions][]) or npm `npm install cldr-data`. For more information, see:
- https://github.com/rxaviers/cldr-data-npm
- https://github.com/rxaviers/cldr-data-bower
[detailed instructions]: https://github.com/rxaviers/cldr-data-bower
## How do I load CLDR data into Globalize?
The short answer is by using `Globalize.load()` and passing the JSON data as the first argument. Below, follow several examples on how this could be accomplished.
Example of embedding CLDR JSON data:
```html
<script>
Globalize.load({
main: {
en: {
...
}
},
supplemental: {
likelySubtags: {
...
},
timeDate: {
...
},
weekData: {
...
}
}
});
</script>
```
Example of loading it dynamically:
```html
<script src="jquery.js"></script>
<script>
// Use $.getJSON instead of $.get if your server is not configured to return the
// right MIME type for .json files.
$.when(
$.get( "cldr/main/en/ca-gregorian.json" ),
$.get( "cldr/supplemental/likelySubtags.json" ),
$.get( "cldr/supplemental/timeData.json" ),
$.get( "cldr/supplemental/weekData.json" )
).then(function() {
// Normalize $.get results, we only need the JSON, not the request statuses.
return [].slice.apply( arguments, [ 0 ] ).map(function( result ) {
return result[ 0 ];
});
}).then( Globalize.load ).then(function() {
// Your code goes here.
});
</script>
```
Example using AMD (also see our [functional tests](../../test/functional.js)):
```javascript
define([
"globalize",
"json!cldr-data/main/en/ca-gregorian.json",
"json!cldr-data/supplemental/likelySubtags.json",
"json!cldr-data/supplemental/timeData.json",
"json!cldr-data/supplemental/weekData.json",
"globalize/date"
], function( Globalize, enCaGregorian, likelySubtags, timeData, weekData ) {
Globalize.load(
enCaGregorian,
likelySubtags,
timeData,
weekData
);
// Your code goes here.
});
```
Example using Node.js:
```javascript
var Globalize = require( "globalize" );
Globalize.load(
require( "cldr-data/main/en/ca-gregorian" ),
require( "cldr-data/supplemental/likelySubtags" ),
require( "cldr-data/supplemental/timeData" ),
require( "cldr-data/supplemental/weekData" )
);
```

View File

@@ -0,0 +1,9 @@
## E_DEFAULT_LOCALE_NOT_DEFINED
Thrown when any static method, eg. `Globalize.formatNumber()` is used prior to setting the Global locale with `Globalize.locale( <locale> )`.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_DEFAULT_LOCALE_NOT_DEFINED` |

View File

@@ -0,0 +1,14 @@
## E_INVALID_CLDR
Thrown when a CLDR item has an invalid or unexpected value.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_INVALID_CLDR` |
| description | Reason why the data was considered invalid |
- description "Missing rules to deduce plural form of \`{value}\`"
Thrown when the plural form (also known as plural group) is not found for the given value. This error is very unlikely to occur and is related to incomplete or invalid CLDR `supplemental/plurals-type-cardinal/{language}` data.

View File

@@ -0,0 +1,12 @@
## E_INVALID_PAR_TYPE
Thrown when a parameter has an invalid type on any static or instance methods.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_INVALID_PAR_TYPE` |
| name | Name of the invalid parameter |
| value | Invalid value |
| expected | Expected type |

View File

@@ -0,0 +1,11 @@
## E_INVALID_PAR_VALUE
Thrown for certain parameters when the type is correct, but the value is invalid. Currently, the only parameter with such validation is the date format (for either format and parse). Format allows [certain variants](../api/date/date-formatter.md#parameters), if it's none of them, error is thrown.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_INVALID_PAR_VALUE` |
| name | Name of the invalid parameter |
| value | Invalid value |

View File

@@ -0,0 +1,11 @@
## E_MISSING_CLDR
Thrown when any required CLDR item is NOT found.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_MISSING_CLDR` |
| path | Missing CLDR item path |

View File

@@ -0,0 +1,10 @@
## E_MISSING_PARAMETER
Thrown when a required parameter is missing on any static or instance methods.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_MISSING_PARAMETER` |
| name | Name of the missing parameter |

View File

@@ -0,0 +1,9 @@
## E_MISSING_PLURAL_MODULE
Thrown when plural module is needed, but not loaded, eg. formatting currencies using plural messages.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_MISSING_PLURAL_MODULE` |

View File

@@ -0,0 +1,11 @@
## E_PAR_MISSING_KEY
Thrown when a parameter misses a required key.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_PAR_MISSING_KEY` |
| key | Name of the missing parameter's key |
| name | Name of the missing parameter |

View File

@@ -0,0 +1,13 @@
## E_PAR_OUT_OF_RANGE
Thrown when a parameter is not within a valid range of values.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_PAR_OUT_OF_RANGE` |
| name | Name of the invalid parameter |
| value | Invalid value |
| minimum | Minimum value of the valid range |
| maximum | Maximum value of the valid range |

View File

@@ -0,0 +1,10 @@
## E_UNSUPPORTED
Thrown for unsupported features, eg. to format unsupported date patterns.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_UNSUPPORTED` |
| feature | Description of the unsupported feature |

View File

@@ -0,0 +1,64 @@
# Migrating from Globalize 0.x
Globalize 0.x came with a bundled locale for US English, and optional files for various other locales. Globalize 1.x uses CLDR for the locale data, and it doesn't bundle any locale data. Check out the documentation for loading CLDR data in 1.x to learn more about that. If you were only using the bundle locale, you only need to load CLDR data for US English. If you were loading other locales, make sure you load those from CLDR as well.
On the API side, things have also changed, to simplify usage, remove ambiguity and add features. The rest of this document provides a brief function-by-function list.
If you still need help with migration, let us know. We may extend this guide later as necessary.
## Globalize.addCultureInfo()
This method is replaced by `Globalize.loadMessages( json )`. If you were using it for anything except message translations, you may also need to use `Globalize.load`.
## Globalize.cultures
This property is gone. You can use Cldrjs to traverse CLDR directly.
## Globalize.culture( [locale] )
This method is replaced by the `Globalize.locale( [locale|cldr] )` method. Call it without arguments to retrieve the default locale, call it with a string argument to set the default locale.
## Globalize.findClosestCulture
This method is gone, there is no replacement. If you still need this method, create an issue with your usecase.
## Globalize.format
Replaced by three separate methods:
* `.formatNumber( value [, options] )`
* `.formatCurrency( value, currency [, options] )`
* `.formatDate( value, pattern )`
See their respective documentation for usage details. Note that the number and date formats are now based on CLDR, using the options and patterns standardized by Unicode. We don't currently have documentation for migrating these formats.
## Globalize.localize
Replaced by `.formatMessage( path [, variables ] )`. The new API is quite different and provides much more than just value-lookup. See their respective documentation for usage details.
## Globalize.parseInt/parseFloat
Replaced by `.parseNumber( value [, options] )`. So where you might have previously executed:
```js
Globalize( "en" ).parseFloat( "123,456.789" )
// > 123456.789
```
You could now execute:
```js
Globalize( "en" ).parseNumber( "123,456.789" )
// > 123456.789
```
`parseNumber` is an alias for [`.numberParser( [options] )( value )`](api/number/number-parser.md). So you could also do this:
```js
Globalize( "en" ).numberParser()( "123,456.789" )
// > 123456.789
```
## Globalize.parseDate
This method still exists, and the signature is almost the same: `.parseDate( value, pattern )`. Note that `pattern` indicates just a single "format", where Globalize 0.x supported multiple of those "formats".