• This repository has been archived on 25/Jan/2022
  • Stars
    star
    215
  • Rank 183,925 (Top 4 %)
  • Language
    HTML
  • Created about 9 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

`Intl.RelativeTimeFormat` specification [draft]

Intl.RelativeTimeFormat API Specification [draft]

Overview

Motivation

Due to common use, relative time–formatted values exist in a majority of websites and are available for the majority of frameworks (e.g., React, via react-intl and react-globalize; Ember, via ember-intl). Popular localization libraries like Moment.js, Format.js, Globalize, and others have implemented a formatting process for relative time values as well.

It is highly probable that the majority of current relative time formatting implementations require a large portion of CLDR raw or compiled data to format relative time values. Bringing this into the platform will improve performance of the web and developer productivity as they no longer have to bring extra weight to format relative time values.

Usage examples

The following example shows how to create a relative time formatter using the English language.

Units : "year", "quarter", "month", "week", "day", "hour", "minute" and "second".

// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
    localeMatcher: "best fit", // other values: "lookup"
    numeric: "always", // other values: "auto"
    style: "long", // other values: "short" or "narrow"
});


// Format relative time using negative value (-1).
rtf.format(-1, "day");
// > "1 day ago"

// Format relative time using positive  value (1).
rtf.format(1, "day");
// > "in 1 day"

Note: If numeric:auto option is passed, it will produce the string yesterday or tomorrow instead of 1 day ago or in 1 day, this allows to not always have to use numeric values in the output.

// Create a relative time formatter in your locale
// with numeric: "auto" option value passed in.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

// Format relative time using negative value (-1).
rtf.format(-1, "day");
// > "yesterday"

// Format relative time using positive day unit (1).
rtf.format(1, "day");
// > "tomorrow"

Implementation Status

Stage 4

Implementation Progress

Backpointers

Polyfills

There're several polyfills available which are listed in the comparison table below. The functionality of all polyfills is the same in terms of the API: they only differ in their implementation details like the way the polyfill is imported or the way locales are loaded or whether the implementation passes the Official ECMAScript Conformance Test for the complete coverage of all possible edge cases.

Polyfill intl-relative-time-format @formatjs/intl-relativetimeformat relative-time-format
Requirements Requirements: Intl.NumberFormat, Intl.PluralRules, Intl.getCanonicalLocales, Object.is, WeakMap and others Requirements: Intl.NumberFormat, Intl.PluralRules, Object.is No requirements
Core bundle size (gzipped) 3.2 kB 2.7 kB 3.0 kB
Passes the Official ECMAScript Conformance Test ✔️ Yes ✔️ Yes No

Authors

  • Caridy Patiño (@caridy)
  • Eric Ferraiuolo (@ericf)
  • Zibi Braniecki (@zbraniecki)
  • Rafael Xavier (@rxaviers)
  • Daniel Ehrenberg (@littledan)

Reviewers

TBD

Proposal

Intl.RelativeTimeFormat is a low level API to facilitate libraries and frameworks to format relative time in a localized fashion by providing internationalized messages for date and time fields, using customary word or phrase when available.

Spec

You can view the spec text or rendered as HTML.

Technical Design

This proposal is based on the ICU Relative Date Time Formatter and on the Unicode CLDR Calendar Fields Relative values:

It is also based on the LDML spec, C.11 Language Plural Rules:

Prior Art

Java
  • ICU: com.ibm.icu.impl.RelativeDateFormat
  • org.ocpsoft.prettytime.PrettyTime
Ruby
include ActionView::Helpers::DateHelper
def index
  @friendly_date = time_ago_in_words(Date.today - 1)
end

Naming

For consistency with Intl.NumberFormat and Intl.DateTimeFormat, we have chosen a similar form for this new feature. The creation of an Intl.RelativeTimeFormat instance is an expensive operation that requires resolution of locale data, and most likely, libraries will attempt to cache those instances, just like they do for Intl.NumberFormat and Intl.DateTimeFormat.

We have also chosen style as the primary form of switching between different formatting forms for consistency with Intl.NumberFormat and Intl.DateTimeFormat.

Since this new feature does format a provided value just like instances of Intl.NumberFormat, and Intl.DateTimeFormat, we have chosen the same form by providing a format(value) method of the instance, which returns a formatted string value.

Take number instead of date object for input

Relative time is used to display date distances, therefore the natural form of input should intuitively be a date object. Although, in this API we chose to take a number instead due to the following reasons:

  1. Basically, taking a number as input for the format method instead of a date object significantly simplifies the scope of this proposal while it still fully addresses the main objective which is to provide i18n building blocks to address this problem realm.
  2. Taking a date object means we should implement the comparison logic (relative time is about date distance between target and source dates). The source date is usually now, but not always. We would have to address modifying that. See #4.
  3. Taking a date object also means we should allow for different calendar calculations, which implies Date should support it. See #6 and #13.
  4. Taking a date object suggests we should be able to implement a bestFit algorithm, which has its own API challenges with respect to standardizing an approach that works for all cases. See #7, #14, and #15. We'd probably need to provide a flag for users to fill, with no default setting, to choose between options for calendar calculation.

Take number as input rather than exposing the underlying database

An idea has been floated, in the context of "the extensible web", of just exposing the engine's copy of the CLDR database rather than a higher-level interface would be better. In the case of this specification, there is already a JS object model ready to go--the locale database is represented internally in the spec as a JavaScript object.

However, we opted not to go that route for a couple reasons:

  • As described above, the API is already fairly low-level, taking numbers rather than dates.
  • Although there are clearly use cases for different policies about rounding dates into units, we haven't come across a use case for seeing the underlying data.
  • This new API is analogous to previous APIs, which should be useful for people learning the system.
  • CLDR changes schema over time; if the data model improves, implementations can transparently upgrade users to better results with the same API. However, if we freeze things to the current logic, the old data model would need to be emulated.

Difference between this and UnitFormat

The fundamental difference between RelativeTimeFormat and UnitFormat is that RelativeTimeFormat displays a relative unit (e.g., 5 days ago or in 5 days) while UnitFormat displays an absolute unit (e.g., -5 meters or 5 meters). Note that RelativeTimeFormat uses different internationalized messages based on the value sign direction, while UnitFormat uses the same internationalized message for all values.

Countdowns, e.g., 15 days, 0 hours, 27 minutes, and 52 seconds

A countdown for example is a mix of UnitFormat and ListFormat, and is not a RelativeTimeFormat.

NumberFormat options (e.g., useGrouping, maximumFractionDigits)

RelativeTimeFormat messages may include number parts (e.g., the 1,000 in 1,000 days ago), which are formatted using the NumberFormat default options.

In this design, we didn't find any use case that could justify allowing to change/override these NumberFormat default options. Therefore, RelativeTimeFormat doesn't include any NumberFormat option.

API

Intl.RelativeTimeFormat([locales[, options]])

The Intl.RelativeTimeFormat object is a constructor for objects that enable language-sensitive relative time formatting.

locales

Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page.

options

Optional. An object with some or all of the following properties:

localeMatcher

The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see the Intl page.

numeric

The format of output message. Possible values are "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). "auto" allows to not always have to use numeric values in the output.

style

The length of the internationalized message. Possible values are: "long" (default, e.g., in 1 month); "short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). The narrow style could be similar to the short style for some locales.

Example

// Create a relative time formatter in your locale.
let rtf = new Intl.RelativeTimeFormat("en", {
    localeMatcher: "best fit", // other values: "lookup"
    numeric: "always", // other values: "auto"
    style: "long", // other values: "short" or "narrow"
});

Intl.RelativeTimeFormat.prototype.format(value, unit)

The Intl.RelativeTimeFormat.prototype.format method formats a value and unit according to the locale and formatting options of this Intl.RelativeTimeFormat object.

While this method automatically provides the correct plural forms, the grammatical form is otherwise as neutral as possible. It is the caller's responsibility to handle cut-off logic such as deciding between displaying "in 7 days" or "in 1 week". This API does not support relative dates involving compound units. e.g "in 5 days and 4 hours".

value

Numeric value to use in the internationalized relative time message.

unit

Unit to use in the relative time internationalized message. Possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". Plural forms are also permitted.

Example

const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

// Format relative time using the day unit.
rtf.format(-1, "day");
// > "yesterday"

rtf.format(2.15, "day");
// > "in 2.15 days"

rtf.format(100, "day");
// > "in 100 days"

rtf.format(0, "day");
// > "today"

rtf.format(-0, "day");
// > "today"

Additionally, by combining the class option style and unit, you can achieve any of the following results:

last year
this year
next year
in 1 year
in 2 years
1 year ago
2 years ago
yr.
last yr.
this yr.
next yr.
in 1 yr.
in 2 yr.
1 yr. ago
2 yr. ago
last quarter
this quarter
next quarter
in 1 quarter
in 2 quarters
1 quarter ago
2 quarters ago
last qtr.
this qtr.
next qtr.
in 1 qtr.
in 2 qtrs.
1 qtr. ago
2 qtrs. ago
last month
this month
next month
in 1 month
in 2 months
1 month ago
2 months ago
last mo.
this mo.
next mo.
in 1 mo.
in 2 mo.
1 mo. ago
2 mo. ago
last week
this week
next week
in 1 week
in 2 weeks
1 week ago
2 weeks ago
last wk.
this wk.
next wk.
in 1 wk.
in 2 wk.
1 wk. ago
2 wk. ago
in 1 day
in 2 days
1 day ago
2 days ago
yesterday
today
tomorrow
in 1 hour
in 2 hours
1 hour ago
2 hours ago
in 1 hr.
in 2 hr.
1 hr. ago
2 hr. ago
in 1 minute
in 2 minutes
1 minute ago
2 minutes ago
in 1 min.
in 2 min.
1 min. ago
2 min. ago
in 1 second
in 2 seconds
1 second ago
2 seconds ago
in 1 sec.
in 1 sec.
1 sec. ago
2 sec. ago
now

Intl.RelativeTimeFormat.prototype.formatToParts(value, unit)

The Intl.RelativeTimeFormat.prototype.formatToParts method is a version of the format method which it returns an array of objects which represent "parts" of the object, separating the formatted number into its consituent parts and separating it from other surrounding text. These objects have two properties: type a NumberFormat formatToParts type, and value, which is the String which is the component of the output. If a "part" came from NumberFormat, it will have a unit property which indicates the unit being formatted; literals which are part of the larger frame will not have this property.

Example

const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

// Format relative time using the day unit.
rtf.formatToParts(-1, "day");
// > [{ type: "literal", value: "yesterday"}]

rtf.formatToParts(100, "day");
// > [{ type: "literal", value: "in " }, { type: "integer", value: "100", unit: "day" }, { type: "literal", value: " days" }]

Development

Render Spec

npm install
npm run build
open index.html

More Repositories

1

proposals

Tracking ECMAScript Proposals
17,177
star
2

ecma262

Status, process, and documents for ECMA-262
HTML
14,437
star
3

proposal-pipeline-operator

A proposal for adding a useful pipe operator to JavaScript.
HTML
7,534
star
4

proposal-pattern-matching

Pattern matching syntax for ECMAScript
HTML
5,498
star
5

proposal-optional-chaining

HTML
4,942
star
6

proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
JavaScript
4,252
star
7

proposal-signals

A proposal to add signals to JavaScript.
3,387
star
8

proposal-temporal

Provides standard objects and functions for working with dates and times.
HTML
3,321
star
9

proposal-observable

Observables for ECMAScript
JavaScript
3,058
star
10

proposal-decorators

Decorators for ES6 classes
2,640
star
11

proposal-record-tuple

ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!
HTML
2,496
star
12

test262

Official ECMAScript Conformance Test Suite
JavaScript
2,073
star
13

proposal-dynamic-import

import() proposal for JavaScript
HTML
1,863
star
14

proposal-bind-operator

This-Binding Syntax for ECMAScript
1,742
star
15

proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
HTML
1,722
star
16

proposal-async-await

Async/await for ECMAScript
HTML
1,578
star
17

proposal-object-rest-spread

Rest/Spread Properties for ECMAScript
HTML
1,493
star
18

proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
HTML
1,429
star
19

proposal-iterator-helpers

Methods for working with iterators in ECMAScript
HTML
1,307
star
20

proposal-nullish-coalescing

Nullish coalescing proposal x ?? y
HTML
1,232
star
21

proposal-top-level-await

top-level `await` proposal for ECMAScript (stage 4)
HTML
1,083
star
22

proposal-partial-application

Proposal to add partial application to ECMAScript
HTML
1,002
star
23

proposal-do-expressions

Proposal for `do` expressions
HTML
990
star
24

proposal-binary-ast

Binary AST proposal for ECMAScript
961
star
25

agendas

TC39 meeting agendas
JavaScript
952
star
26

proposal-built-in-modules

HTML
891
star
27

proposal-async-iteration

Asynchronous iteration for JavaScript
HTML
857
star
28

proposal-explicit-resource-management

ECMAScript Explicit Resource Management
JavaScript
746
star
29

proposal-set-methods

Proposal for new Set methods in JS
HTML
655
star
30

proposal-string-dedent

TC39 Proposal to remove common leading indentation from multiline template strings
HTML
614
star
31

proposal-operator-overloading

JavaScript
610
star
32

proposal-import-attributes

Proposal for syntax to import ES modules with assertions
HTML
591
star
33

proposal-async-context

Async Context for JavaScript
HTML
587
star
34

proposal-bigint

Arbitrary precision integers in JavaScript
HTML
561
star
35

ecmascript_simd

SIMD numeric type for EcmaScript
JavaScript
540
star
36

ecma402

Status, process, and documents for ECMA 402
HTML
529
star
37

proposal-slice-notation

HTML
523
star
38

proposal-change-array-by-copy

Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.
HTML
511
star
39

notes

TC39 meeting notes
JavaScript
496
star
40

proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
HTML
489
star
41

proposal-iterator.range

A proposal for ECMAScript to add a built-in Iterator.range()
HTML
483
star
42

proposal-decimal

Built-in exact decimal numbers for JavaScript
HTML
477
star
43

proposal-uuid

UUID proposal for ECMAScript (Stage 1)
JavaScript
463
star
44

proposal-module-expressions

HTML
433
star
45

proposal-throw-expressions

Proposal for ECMAScript 'throw' expressions
JavaScript
425
star
46

proposal-UnambiguousJavaScriptGrammar

413
star
47

proposal-weakrefs

WeakRefs
HTML
409
star
48

proposal-array-grouping

A proposal to make grouping of array items easier
HTML
407
star
49

proposal-error-cause

TC39 proposal for accumulating errors
HTML
380
star
50

proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Shell
376
star
51

proposal-ecmascript-sharedmem

Shared memory and atomics for ECMAscript
HTML
374
star
52

proposal-module-declarations

JavaScript Module Declarations
HTML
369
star
53

proposal-first-class-protocols

a proposal to bring protocol-based interfaces to ECMAScript users
352
star
54

proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
HTML
351
star
55

proposal-global

ECMAScript Proposal, specs, and reference implementation for `global`
HTML
346
star
56

proposal-private-methods

Private methods and getter/setters for ES6 classes
HTML
345
star
57

proposal-numeric-separator

A proposal to add numeric literal separators in JavaScript.
HTML
330
star
58

proposal-private-fields

A Private Fields Proposal for ECMAScript
HTML
319
star
59

tc39.github.io

Get involved in specifying JavaScript
HTML
318
star
60

proposal-object-from-entries

TC39 proposal for Object.fromEntries
HTML
318
star
61

proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled
HTML
314
star
62

proposal-await.ops

Introduce await.all / await.race / await.allSettled / await.any to simplify the usage of Promises
HTML
310
star
63

proposal-regex-escaping

Proposal for investigating RegExp escaping for the ECMAScript standard
JavaScript
309
star
64

proposal-export-default-from

Proposal to add `export v from "mod";` to ECMAScript.
HTML
306
star
65

proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
HTML
302
star
66

proposal-promise-finally

ECMAScript Proposal, specs, and reference implementation for Promise.prototype.finally
HTML
279
star
67

proposal-json-modules

Proposal to import JSON files as modules
HTML
272
star
68

proposal-asset-references

Proposal to ECMAScript to add first-class location references relative to a module
270
star
69

proposal-cancellation

Proposal for a Cancellation API for ECMAScript
HTML
267
star
70

proposal-promise-with-resolvers

HTML
255
star
71

proposal-string-replaceall

ECMAScript proposal: String.prototype.replaceAll
HTML
253
star
72

proposal-export-ns-from

Proposal to add `export * as ns from "mod";` to ECMAScript.
HTML
242
star
73

proposal-structs

JavaScript Structs: Fixed Layout Objects
230
star
74

proposal-ses

Draft proposal for SES (Secure EcmaScript)
HTML
223
star
75

proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
HTML
214
star
76

proposal-flatMap

proposal for flatten and flatMap on arrays
HTML
214
star
77

proposal-defer-import-eval

A proposal for introducing a way to defer evaluate of a module
HTML
208
star
78

ecmarkup

An HTML superset/Markdown subset source format for ECMAScript and related specifications
TypeScript
201
star
79

proposal-promise-any

ECMAScript proposal: Promise.any
HTML
200
star
80

proposal-optional-chaining-assignment

`a?.b = c` proposal
186
star
81

proposal-decorators-previous

Decorators for ECMAScript
HTML
184
star
82

proposal-smart-pipelines

Old archived draft proposal for smart pipelines. Go to the new Hack-pipes proposal at js-choi/proposal-hack-pipes.
HTML
181
star
83

proposal-array-from-async

Draft specification for a proposed Array.fromAsync method in JavaScript.
HTML
178
star
84

proposal-upsert

ECMAScript Proposal, specs, and reference implementation for Map.prototype.upsert
HTML
176
star
85

proposal-collection-methods

HTML
171
star
86

proposal-array-filtering

A proposal to make filtering arrays easier
HTML
171
star
87

proposal-ptc-syntax

Discussion and specification for an explicit syntactic opt-in for Tail Calls.
HTML
169
star
88

proposal-extractors

Extractors for ECMAScript
JavaScript
166
star
89

proposal-error-stacks

ECMAScript Proposal, specs, and reference implementation for Error.prototype.stack / System.getStack
HTML
166
star
90

proposal-intl-duration-format

164
star
91

how-we-work

Documentation of how TC39 operates and how to participate
161
star
92

proposal-Array.prototype.includes

Spec, tests, reference implementation, and docs for ESnext-track Array.prototype.includes
HTML
157
star
93

proposal-promise-try

ECMAScript Proposal, specs, and reference implementation for Promise.try
HTML
154
star
94

proposal-extensions

Extensions proposal for ECMAScript
HTML
150
star
95

proposal-hashbang

#! for JS
HTML
148
star
96

proposal-import-meta

import.meta proposal for JavaScript
HTML
146
star
97

proposal-intl-segmenter

Unicode text segmentation for ECMAScript
HTML
146
star
98

proposal-resizablearraybuffer

Proposal for resizable array buffers
HTML
145
star
99

proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
HTML
143
star
100

eshost

A uniform wrapper around a multitude of ECMAScript hosts. CLI: https://github.com/bterlson/eshost-cli
JavaScript
142
star