In my React app, I have to show info saying create 1 hour ago or 1 day ago and also plural as 10 minutes ago or 3 days ago. To achieve that I'm trying to use this API FormatJS and in the specific intl.formatRelativeTime()
What I tried so far is something like that
const CreatedConsetee = ({ date }) => {
// date = 2021-04-26T14:21:51.771Z
const intl = useIntl();
const parsedDate = new Date(date);
const dateFormat = intl.formatRelativeTime(parsedDate, 'hour', {
style: 'long',
});
return <>{dateFormat}</>;
};
The result is of the above is like this
in 1,619,446,911,771 hours
Whatever is it always that big number and I have no idea how to make it right.
The expected behavior I want is that I got a message saying created 7 days ago
the same if we have 1 hour 1 minute 1 day and plural forms 2 hours 2 minutes 2 days.
You would have to take the current time and diff the tiem you are formatting to get the milliseconds.
Now, you need to figure out the closest unit to round down to and format using that unit.
Just swap
Intl.RelativeTimeFormat
forintl.formatRelativeTime
where applicable, but the algorithm should remain the same.Here is a version of the code above written in React: