Skip to content

Commit

Permalink
feat: use Intl.RelativeTimeFormat for legacy namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
wmui51 committed Oct 3, 2023
1 parent cd13fa2 commit ae09168
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/timestamp/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hig/timestamp",
"version": "2.2.0",
"version": "2.3.0",
"description": "HIG Timestamp",
"author": "Autodesk Inc.",
"license": "Apache-2.0",
Expand Down
27 changes: 25 additions & 2 deletions packages/timestamp/src/Timestamp.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,14 @@ const Timestamp = (props) => {
};

const humanizeTimestamp = () => {
const { plural, timeDescriptors, timestamp } = props;
const { plural, relativeTimeFormatOptions, timeDescriptors, timestamp } =
props;
const asSeconds = Date.parse(timestamp) / 1000; // TODO: handle future timestamps, or bad input?
const nowAsSeconds = new Date().valueOf() / 1000;
const rtf = new Intl.RelativeTimeFormat(
relativeTimeFormatOptions?.locales,
relativeTimeFormatOptions?.options
);

const timeDifference = nowAsSeconds - asSeconds;
let distance;
Expand Down Expand Up @@ -99,7 +104,9 @@ const Timestamp = (props) => {
: timeDescriptors.year;
}

return getTimestampSequence(distance, ellapsedDescriptor);
return relativeTimeFormatOptions
? rtf.format(-distance, ellapsedDescriptor)
: getTimestampSequence(distance, ellapsedDescriptor);
};

return (
Expand Down Expand Up @@ -130,6 +137,22 @@ Timestamp.propTypes = {
* If "true" then it adds an "s" to the end of the time unit
*/
plural: PropTypes.bool,
/**
* These are the options passed to the
* Intl.RelativeTimeFormat() constructor
* If this prop is used then the following props
* will be ignored: plural, timestampSequence,
* timeDescriptors, wordspace
*/
relativeTimeFormatOptions: PropTypes.shape({
locales: PropTypes.string,
options: PropTypes.shape({
localeMatcher: PropTypes.string,
numberingSystem: PropTypes.string,
style: PropTypes.string,
numeric: PropTypes.string,
}),
}),
/**
* Adds custom/overriding styles
*/
Expand Down
9 changes: 9 additions & 0 deletions packages/timestamp/src/__stories__/Timestamp.new-stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,12 @@ const Template = (args) => {
};

export const Default = Template.bind({});

export const RelativeTimeFormat = Template.bind({});

RelativeTimeFormat.args = {
relativeTimeFormatOptions: {
locales: "es",
},
};
RelativeTimeFormat.storyName = "Relative time format";

0 comments on commit ae09168

Please sign in to comment.