I am facing a problem with the UI and want to show the timestamp distance into 3 hours ago
and 4 hours ago
etc. The timestamp coming from the server with a property named createdAt
which has the following value.
createdAt: "2021-10-27T05:24:37.642Z"
To solve this problem I am using library like date-fns v2.25.0 builtin function formatDistance.
import { formatDistance} from 'date-fns';
const timestamp = createdAt ? new Date(createdAt) : '';
console.log(formatDistance(Date.now(), timestamp, {addSuffix: true}));
But it is giving back the distance in the following words
in about 3 hours
in about 4 hours
instead of
3 hours ago
4 hours ago
What I am doing wrong? If you know any other good library please you can share.
Reverse the arguments:
console.log(formatDistance(timestamp, Date.now(), {addSuffix: true}));