Difference between current time and UTC time format in javascript with Date-fns

Viewed 1842

I am using newsapi.org to get news data and date-fns library. How can I get difference between PublishedTime of article which is in UTC+000 (e.g: 2020-09-13T15:50:00Z) and current datetime? What i have tried:

import { formatDistance } from "date-fns";
timeDistance = (time) => {
  return formatDistance(new Date(), time);
};

where time is a string: e.g: "2020-09-13T15:50:00Z"

Expected result: something like 10 minutes ago, 1 hour ago etc.

1 Answers

This should work:

import formatDistance from 'date-fns/formatDistance';

timeDistance = (time) => {
  return formatDistance(new Date(), new Date(time));
};

console.log(timeDistance('2020-09-13T15:50:00Z'));

Note: make sure you import formatDistance from date-fns/formatDistance to make code splitting easier

Related