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.
You can use any other popular package such as moment, which I do believe have more custom configuration, but if you want to use this package, instead of having to change the formatDistance function, it would be easier to change the result string like:
import { formatDistance } from "date-fns";
const createdAt = "2020-08-27T08:24:37.642Z";
const timestamp = createdAt ? new Date(createdAt) : "";
const distance = formatDistance(Date.now(), timestamp, {addSuffix: true });
console.log(distance.substring(distance.indexOf(distance.match(/\d+/g))));
// => 2 hours ago
Reverse the arguments:
console.log(formatDistance(timestamp, Date.now(), {addSuffix: true}));