Skip to content

Commit

Permalink
Date: Add formatDateToParts (2/2)
Browse files Browse the repository at this point in the history
  • Loading branch information
rxaviers committed Apr 12, 2017
1 parent 6919f43 commit e4234a7
Show file tree
Hide file tree
Showing 27 changed files with 1,009 additions and 724 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,24 @@ Read more details about locale at [UTS#35 locale][].

[Read more...](doc/api/date/date-formatter.md)

- **.dateToPartsFormatter( [options] )`**

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" }`.

```javascript
.dateToPartsFormatter()( new Date() )
// > [
// { "type": "month", "value": "3" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "17" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2017" }
// ]
```

[Read more...](doc/api/date/date-to-parts-formatter.md)

- **`.dateParser( [options] )`**

Return a function that parses a string representing a date into a JavaScript Date object according
Expand Down Expand Up @@ -475,6 +493,10 @@ Read more details about locale at [UTS#35 locale][].

Alias for `.dateFormatter( [options] )( value )`.

- **`.formatDateToParts( value [, options] )`**

Alias for `.dateToPartsFormatter( [options] )( value )`.

- **`.parseDate( value [, options] )`**

Alias for `.dateParser( [options] )( value )`.
Expand Down
2 changes: 1 addition & 1 deletion doc/api/date/date-formatter.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ var enFormatter = Globalize( "en" ).dateFormatter(),
deFormatter = Globalize( "de" ).dateFormatter();

enFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "11/30/2010, 5:55 PM"
// > "11/30/2010"

deFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "30.11.2010"
Expand Down
190 changes: 190 additions & 0 deletions doc/api/date/date-to-parts-formatter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
## .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"`.

- `timeZoneName`

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" }
// ]
// ]
```
2 changes: 1 addition & 1 deletion examples/amd-bower/bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "globalize-hello-world-amd-bower",
"dependencies": {
"cldr-data": "*",
"globalize": ">=1.2.0-a <2.0.0"
"globalize": ">=1.3.0-a <2.0.0"
},
"devDependencies": {
"requirejs": "2.1.14",
Expand Down
1 change: 1 addition & 0 deletions examples/amd-bower/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ <h2>Requirements</h2>
<div id="demo" style="display: none">
<h2>Demo output</h2>
<p>Now: <span id="date"></span></p>
<p>Now: <span id="dateToParts"></span> (note the highlighted month, the markup was added using formatDateToParts)</p>
<p>A number: <span id="number"></span></p>
<p>A currency: <span id="currency"></span></p>
<p>Plural form of <span id="plural-number"></span> is <span id="plural-form"></span></p>
Expand Down
12 changes: 12 additions & 0 deletions examples/amd-bower/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ require([
datetime: "medium"
});

// Use Globalize to format dates to parts.
document.getElementById( "dateToParts" ).innerHTML = en.formatDateToParts( new Date(), {
datetime: "medium"
}).map(function( part ) {
switch(part.type) {
case "month": return "<strong>" + part.value + "</strong>";
default: return part.value;
}
}).reduce(function( memo, value ) {
return memo + value;
});

// Use Globalize to format numbers.
number = en.numberFormatter();
document.getElementById( "number" ).textContent = number( 12345.6789 );
Expand Down
17 changes: 17 additions & 0 deletions examples/app-npm-webpack/app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,21 @@ document.getElementById( "currency" ).textContent = currencyFormatter( 69900 );
var dateFormatter = Globalize.dateFormatter({ datetime: "medium" });
document.getElementById( "date" ).textContent = dateFormatter( new Date() );

var _dateToPartsFormatter = Globalize.dateToPartsFormatter({ datetime: "medium" });
var dateToPartsFormatter = function( value ) {
return _dateToPartsFormatter( value, {
datetime: "medium"
}).map(function( part ) {
switch(part.type) {
case "month": return "<strong>" + part.value + "</strong>";
default: return part.value;
}
}).reduce(function( memo, value ) {
return memo + value;
});
};
document.getElementById( "date-to-parts" ).innerHTML = dateToPartsFormatter( new Date() );

var relativeTimeFormatter = Globalize.relativeTimeFormatter( "second" );
document.getElementById( "relative-time" ).textContent = relativeTimeFormatter( 0 );

Expand All @@ -22,6 +37,7 @@ document.getElementById( "intro-1" ).textContent = Globalize.formatMessage( "int
document.getElementById( "number-label" ).textContent = Globalize.formatMessage( "number-label" );
document.getElementById( "currency-label" ).textContent = Globalize.formatMessage( "currency-label" );
document.getElementById( "date-label" ).textContent = Globalize.formatMessage( "date-label" );
document.getElementById( "date-to-parts-label" ).textContent = Globalize.formatMessage( "date-to-parts-label" );
document.getElementById( "relative-time-label" ).textContent = Globalize.formatMessage( "relative-time-label" );
document.getElementById( "unit-label" ).textContent = Globalize.formatMessage( "unit-label" );
document.getElementById( "message-1" ).textContent = Globalize.formatMessage( "message-1", {
Expand All @@ -44,6 +60,7 @@ document.getElementById( "demo" ).style.display = "block";
setInterval(function() {
var elapsedTime = +( ( startTime - new Date() ) / 1000 ).toFixed( 0 );
document.getElementById( "date" ).textContent = dateFormatter( new Date() );
document.getElementById( "date-to-parts" ).innerHTML = dateToPartsFormatter( new Date() );
document.getElementById( "relative-time" ).textContent = relativeTimeFormatter( elapsedTime );
document.getElementById( "message-1" ).textContent = Globalize.formatMessage( "message-1", {
currency: currencyFormatter( 69900 ),
Expand Down
4 changes: 4 additions & 0 deletions examples/app-npm-webpack/index-template.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ <h2>Requirements</h2>
<td><span id="date-label">Standalone Date</span></td>
<td>"<span id="date"></span>"</td>
</tr>
<tr>
<td><span id="date-to-parts-label">Standalone Date (note the highlighted month, the markup was added using formatDateToParts)</span></td>
<td>"<span id="date-to-parts"></span>"</td>
</tr>
<tr>
<td><span id="relative-time-label">Standalone Relative Time</span></td>
<td>"<span id="relative-time"></span>"</td>
Expand Down
1 change: 1 addition & 0 deletions examples/app-npm-webpack/messages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"number-label": "Zahl",
"currency-label": "Währung",
"date-label": "Datum",
"date-to-parts-label": "Datum (beachten Sie den hervorgehobenen Monat, das Markup wurde mit dateToPartsFormatter hinzugefügt)",
"relative-time-label": "Relative Zeit",
"unit-label": "Einheit",
"message-1": "Ein Beispiel mit Zahl \"{number}\", Währung \"{currency}\", Datum \"{date}\", relative Zeit \"{relativeTime}\", und Einheit \"{unit}\".",
Expand Down
1 change: 1 addition & 0 deletions examples/app-npm-webpack/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"number-label": "Number",
"currency-label": "Currency",
"date-label": "Date",
"date-to-parts-label": "Date (note the highlighted month, the markup was added using formatDateToParts)",
"relative-time-label": "Relative Time",
"unit-label": "Unit",
"message-1": "An example of a message using mixed number \"{number}\", currency \"{currency}\", date \"{date}\", relative time \"{relativeTime}\", and unit \"{unit}\".",
Expand Down
1 change: 1 addition & 0 deletions examples/app-npm-webpack/messages/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"number-label": "Número",
"currency-label": "Moneda",
"date-label": "Fecha",
"date-to-parts-label": "Fecha (note el mes destacado en negro, el marcador de html se agregó utilizando dateToPartsFormatter)",
"relative-time-label": "Tiempo Relativo",
"unit-label": "Unidad",
"message-1": "Un ejemplo de mensaje usando números mixtos \"{number}\", monedas \"{currency}\", fechas \"{date}\", tiempo relativo \"{relativeTime}\", y unidades \"{unit}\".",
Expand Down
1 change: 1 addition & 0 deletions examples/app-npm-webpack/messages/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"number-label": "Número",
"currency-label": "Moeda",
"date-label": "Data",
"date-to-parts-label": "Data (note o mês em negrito, a marcação HTML foi adicionada usando formatDateToParts)",
"relative-time-label": "Tempo relativo",
"unit-label": "Unit",
"message-1": "Um exemplo de mensagem com mistura de número \"{number}\", moeda \"{currency}\", data \"{date}\", tempo relativo \"{relativeTime}\", e unidade \"{unit}\".",
Expand Down
4 changes: 2 additions & 2 deletions examples/app-npm-webpack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"private": true,
"devDependencies": {
"cldr-data": ">=25",
"globalize": ">=1.2.0-a <2.0.0",
"globalize-webpack-plugin": "0.3.x",
"globalize": ">=1.3.0-a <2.0.0",
"globalize-webpack-plugin": ">=0.4.0-a <0.5.0",
"html-webpack-plugin": "^1.1.0",
"nopt": "^3.0.3",
"webpack": "^1.9.0",
Expand Down
12 changes: 12 additions & 0 deletions examples/globalize-compiler/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ document.getElementById( "date" ).textContent = Globalize.formatDate( new Date()
datetime: "medium"
});

// Use Globalize to format dates to parts.
document.getElementById( "dateToParts" ).innerHTML = Globalize.formatDateToParts( new Date(), {
datetime: "medium"
}).map(function( part ) {
switch(part.type) {
case "month": return "<strong>" + part.value + "</strong>";
default: return part.value;
}
}).reduce(function( memo, value ) {
return memo + value;
});

// Use Globalize to format numbers.
number = Globalize.numberFormatter();
document.getElementById( "number" ).textContent = number( 12345.6789 );
Expand Down
1 change: 1 addition & 0 deletions examples/globalize-compiler/development.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ <h2>Requirements</h2>
<div id="demo" style="display: none">
<h2>Demo output</h2>
<p>Now: <span id="date"></span></p>
<p>Now: <span id="dateToParts"></span> (note the highlighted month, the markup was added using formatDateToParts)</p>
<p>A number: <span id="number"></span></p>
<p>A currency: <span id="currency"></span></p>
<p>Plural form of <span id="plural-number"></span> is <span id="plural-form"></span></p>
Expand Down
Loading

0 comments on commit e4234a7

Please sign in to comment.