Use of timeago function in React JS
Timeago function use for show difference between current date timestamp and old timestamp. today i am going to show you how to use time ago function for show posted time for example “2 days ago” etc. There is two methods for show ago time.
1. With help of library “react-timeago”
2. With custom created component
1. With help of library “react-timeago”
In React js project we can use react-time-ago library for show time. for use library you should first install library in your project with this command. follow this link for use this library https://www.npmjs.com/package/react-timeago
1 |
npm install react-timeago |
Then require this library in your file and use this code for show ago time.
1 2 3 4 5 6 7 |
import ReactDOM from 'react-dom' import React from 'react' import TimeAgo from 'react-timeago' render(){ return(<TimeAgo date='1618301456781' />) } |
2. And second method is create your own function and use in a component.
This is my way use of this code. you can use this function according to your way. First you need a another common.js file and create a custom function. I created this file because of reuse this function in multiple files.
Common.js file in src/component/ folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
module.exports = { formatTime: (timeCreated)=>{ //console.log(Date.now()) //console.log(timeCreated) var diff = Math.floor((Date.now() - parseInt(timeCreated)) / 1000); var interval = Math.floor(diff / 31536000); if (interval >= 1) { return interval + " years ago"; } interval = Math.floor(diff / 2592000); if (interval >= 1) { return interval + " months ago"; } interval = Math.floor(diff / 604800); if (interval >= 1) { return interval + " weeks ago"; } interval = Math.floor(diff / 86400); if (interval >= 1) { return interval + " days ago"; } interval = Math.floor(diff / 3600); if (interval >= 1) { return interval + " hours ago"; } interval = Math.floor(diff / 60); if (interval >= 1) { return interval + " min ago"; } return "Just Now"; } } |
After that require this component in another component for use this function like this code:
1 2 3 4 5 6 7 8 |
import React from 'react'; import {formatTime} from './Common'; render(){ return( {formatTime(1618301456781)} ) } |
Now you can see result on your screen as time ago format like that.
Output: 2 days ago
This is the function for show time ago format. so if you like this article please share and comment. Thank you, Happy learning 🙂