Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Date-fns format distance is not in correct words

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report

0

Reverse the arguments:

console.log(formatDistance(timestamp, Date.now(), {addSuffix: true}));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!