Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert timestamps to time ago format in react?

Tags:

javascript

suppose that I have an creating time in this format : (2021-06-30 15:36:50.375+03), and I wanna convert it to time ago format like 5 min ago or 2 hours ago , so how can I do that in javascript (react)?

like image 689
Abdalrahman Al-Ashgr Avatar asked Nov 26 '25 12:11

Abdalrahman Al-Ashgr


1 Answers

Doing it by yourself will require a lot of codes, continuous fixing and improvement. You can either use a code snippet of another coder, or better you can use some JS (React/Node/etc.) npm packages, like moment https://www.npmjs.com/package/moment . The advantage of moment is that it's maintained, high quality and very popular, 16M downloads a week, 45.8K stars in Github.

As an example, moment uses the method fromNow():

import moment from 'moment';

// other codes

const timeago = moment(data.created_at).fromNow();

EDIT : (2 packages very light) ----

If you are using just the fromNow feature of Moment package which is heavy and on which tree-shaking doesn't work, and are in need for lighter page size for sep performance, you might wanna use another very light package like: react-timeago: https://www.npmjs.com/package/react-timeago , or timeago-react: https://www.npmjs.com/package/timeago-react which are both way lighter than moment package.

The react-timeago also support automatic update each second, 30s, 60s or any other period specified. Its codes would go like:

import TimeAgo from 'react-timeago';

// auto-updated each 60 seconds
return (
  <TimeAgo
    date={comment.created_at}
    component={Text}
    minPeriod={60}
    style={styles.timeAgo}
  />
);

I'm using react-timeago now. The timeago-react is even more lighter, but I didn't tested it yet.

like image 196
KeitelDOG Avatar answered Nov 29 '25 02:11

KeitelDOG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!