'date should be format automatically according to time in javascript
I have a date string like "2022-05-19T14:44:18.887Z". I am creating a blog website in react so, I just want to show the time how old the post is. so i want to show the time like for example 2 min ago, 2 hrs ago, 10 hrs ago , 1 day ago, 5 days ago then 6 days ago. when As soon as the post becomes 7 days old then it should show the month and year of that post like, May 22. It all the things should be automatically. For this i have used moment library. But i am unable to implement it. Please anyone can help me on this.
Solution 1:[1]
Please try this stuff
import moment from 'moment';
export const _convertTimeHumanReadable = (date) => {
if (!date) return '';
const segs = date.split(' ');
if (segs.length > 1) {
date = segs[0] + 'T' + segs[1];
}
const data = moment(date);
const now = moment();
let result = '';
if (data.format('YYYY') !== now.format('YYYY')) {
result = result + data.format('YYYY');
}
result = result + data.format('M/DD');
return result;
};
export const convertTimeHumanReadable = (date) => {
if (!date) return '';
const now = moment();
const data = moment(date);
const duration = moment.duration(data.diff(now))
if (duration.days() < -1) {
return _convertTimeHumanReadable(date);
}
return duration.humanize(true);
}
This code humanize the date format up to 1 day ago
and if you can change -1 to -7 then humanize up to 7 days ago
if (duration.days() < -1) {
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | devcrazy |
