- Notifications
You must be signed in to change notification settings - Fork30
Formats JavaScript dates to relative time strings (e.g., "3 hours ago").
License
formatjs/intl-relativeformat
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This package has deviated from theIntl.RelativeTimeFormat spec rather heavily. Therefore, we've deprecated this package and add`@formatjs/intl-relativetimeformat as the spec-compliant polyfill.
- All
units(such asday-short) should be migrated similarly to:
newIntlRelativeFormat('en',{units:'second-short'}).format(Date.now()-1000);// will benewIntl.RelativeTimeFormat('en',{style:'short'}).format(-1,'second');newIntlRelativeFormat('en',{units:'day-narrow'}).format(Date.now()-48*3600*1000);// will benewIntl.RelativeTimeFormat('en',{style:'narrow'}).format(-2,'day');
style: numericwill becomenumeric: alwaysper spec (which is also the default)
newIntlRelativeFormat('en',{units:'second-short',style:'numeric'}).format(Date.now()-1000);// will benewIntl.RelativeTimeFormat('en',{style:'short'}).format(-1,'second');
newIntlRelativeFormat('en',{units:'day-narrow',style:'numeric'}).format(Date.now()-48*3600*1000);// will benewIntl.RelativeTimeFormat('en',{style:'narrow'}).format(-2,'day');
style: 'best fit'is a little trickier but we have released@formatjs/intl-utilsto ease the transition:
newIntlRelativeFormat('en',{style:'best fit'}).format(Date.now()-1000);// will beimport{selectUnit}from'@formatjs/intl-utils';constdiff=selectUnit(Date.now()-1000);newIntl.RelativeTimeFormat('en',{numeric:'auto'}).format(diff.value,diff.unit);
newIntlRelativeFormat('en',{style:'best fit'}).format(Date.now()-48*3600*1000);// will beimport{selectUnit}from'@formatjs/intl-utils';constdiff=selectUnit(Date.now()-48*3600*1000);newIntl.RelativeTimeFormat('en',{numeric:'auto'}).format(diff.value,diff.unit);
- If you were using
options.nowinformat, you can useformatjs/intl-utilsto transition as well
newIntlRelativeFormat('en',{style:'best fit'}).format(Date.now()-1000,{now:Date.now()+1000});// will beimport{selectUnit}from'@formatjs/intl-utils';constdiff=selectUnit(Date.now()-1000,Date.now()+1000);newIntl.RelativeTimeFormat('en',{numeric:'auto'}).format(diff.value,diff.unit);
newIntlRelativeFormat('en',{style:'best fit'}).format(Date.now()-48*3600*1000,{now:Date.now()+1000});// will beimport{selectUnit}from'@formatjs/intl-utils';constdiff=selectUnit(Date.now()-48*3600*1000,Date.now()+1000);newIntl.RelativeTimeFormat('en',{numeric:'auto'}).format(diff.value,diff.unit);
Formats JavaScript dates to relative time strings (e.g., "3 hours ago").
This package aims to provide a way to format different variations of relative time. You can use this package in the browser and on the server via Node.js.
This implementation is very similar tomoment.js, in concept, although it provides only formatting features based on the UnicodeCLDR locale data, an industry standard that supports more than 200 languages.
varrf=newIntlRelativeFormat(locales,[options]);
Thelocales can either be a single language tag, e.g.,"en-US" or an array of them from which the first match will be used.options provides a way to control the output of the formatted relative time string.
varoutput=rf.format(someDate,[options]);
The most common way to use this library is to construct anIntlRelativeFormat instance and reuse it many times for formatting different date values; e.g.:
varrf=newIntlRelativeFormat('en-US');varposts=[{id:1,title:'Some Blog Post',date:newDate(1426271670524)},{id:2,title:'Another Blog Post',date:newDate(1426278870524)}];posts.forEach(function(post){console.log(rf.format(post.date));});// => "3 hours ago"// => "1 hour ago"
Style options for
"best fit"("yesterday") and"numeric"("1 day ago") output based on thresholds.Units options for always rendering in a particular unit; e.g. "30 days ago", instead of "1 month ago".
Ability to specify the "now" value from which the relative time is calculated, allowing
format().Format output in relative time strings using`Intl.RelativeTimeFormat
Optimized for repeated calls to an
IntlRelativeFormatinstance'sformat()method.
This package assumes the following capabilities fromIntl:
If your environment does not support those, feel free to grab polyfills:
- https://www.npmjs.com/package/intl-pluralrules
- https://www.npmjs.com/package/@formatjs/intl-relativetimeformat
Install package and polyfill:
npm install intl-relativeformat --save
Simplyrequire() this package:
varIntlRelativeFormat=require('intl-relativeformat');varrf=newIntlRelativeFormat('en');varoutput=rf.format(dateValue);
Install package:
npm install intl-relativeformat --save
Simplyrequire() this package and the specific locales you wish to support in the bundle:
varIntlRelativeFormat=require('intl-relativeformat');
Note: in Node.js, the data for all 200+ languages is loaded along with the library, but when bundling it with Browserify/Webpack, the data is intentionally ignored (seepackage.json for more details) to avoid blowing up the size of the bundle with data that you might not need.
To format a date to relative time, use theIntlRelativeFormat constructor. The constructor takes two parameters:
locales -{String | String[]} - A string with a BCP 47 language tag, or an array of such strings. If you do not provide a locale, the default locale will be used. When an array of locales is provided, each item and its ancestor locales are checked and the first one with registered locale data is returned.See:Locale Resolution for more details.
[options] -{Object} - Optional object with user defined options for format styles.See:Custom Options for more details.
Note: Therf instance should be enough for your entire application, unless you want to use custom options.
IntlRelativeFormat uses a locale resolution process similar to that of the built-inIntl APIs to determine which locale data to use based on thelocales value passed to the constructor. The result of this resolution process can be determined by call theresolvedOptions() prototype method.
The following are the abstract stepsIntlRelativeFormat goes through to resolve the locale value:
If no extra locale data is loaded, the locale willalways resolved to
"en".If locale data is missing for a leaf locale like
"fr-FR", but thereis data for one of its ancestors,"fr"in this case, then its ancestor will be used.If there's data for the specified locale, then that locale will be resolved; i.e.,
varrf=newIntlRelativeFormat('en-US');assert(rf.resolvedOptions().locale==='en-US');// true
The resolved locales are now normalized; e.g.,
"en-us"will resolve to:"en-US".
Note: When an array is provided forlocales, the above steps happen for each item in that array until a match is found.
The optional second argumentoptions provides a way to customize how the relative time will be formatted.
By default, the relative time is computed to the best fit unit, but you can explicitly call it to forceunits to be displayed in"second","second-short","second-narrow","minute","minute-short","minute-narrow","hour","hour-short","hour-narrow","day","day-short","day-narrow","month","month-short","month-narrow","year","year-short" or"year-narrow":
varrf=newIntlRelativeFormat('en',{units:'day'});varoutput=rf.format(dateValue);
As a result, the output will be "70 days ago" instead of "2 months ago".
By default, the relative time is computed as"best fit", which means that instead of "1 day ago", it will display "yesterday", or "in 1 year" will be "next year", etc. But you can force to always use the "numeric" alternative:
varrf=newIntlRelativeFormat('en',{style:'numeric'});varoutput=rf.format(dateValue);
As a result, the output will be "1 day ago" instead of "yesterday".
This method returns an object with the options values that were resolved during instance creation. It currently only contains alocale property; here's an example:
varrf=newIntlRelativeFormat('en-us');console.log(rf.resolvedOptions().locale);// => "en-US"
Notice how the specified locale was the all lower-case value:"en-us", but it was resolved and normalized to:"en-US".
The format method (which takes a JavaScript date or timestamp) and optionaloptions arguments will compare thedate with "now" (oroptions.now), and returns the formatted string; e.g., "3 hours ago" in the corresponding locale passed into the constructor.
varoutput=rf.format(newDate());console.log(output);// => "now"
If you wish to specify a "now" value, it can be provided viaoptions.now and will be used instead of queryingDate.now() to get the current "now" value.
This software is free to use under the Yahoo! Inc. BSD license.See theLICENSE file for license text and copyright information.
About
Formats JavaScript dates to relative time strings (e.g., "3 hours ago").
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors13
Uh oh!
There was an error while loading.Please reload this page.