add precise date time function

This commit is contained in:
plebeius.eth
2023-08-17 13:29:46 +02:00
parent 9085e235e1
commit e76f6a3fe3
3 changed files with 32 additions and 20 deletions
+32 -7
View File
@@ -1,14 +1,39 @@
import en from 'javascript-time-ago/locale/en'
import TimeAgo from 'javascript-time-ago'
TimeAgo.addDefaultLocale(en);
const timeAgo = new TimeAgo('en-US');
const pluralize = (unit, value) => {
return `${value} ${unit}${value > 1 ? 's' : ''}`;
};
const getFormattedTime = (timestamp) => {
try {
return timeAgo.format(timestamp * 1000)
const currentTime = new Date().getTime();
const differenceInMilliseconds = currentTime - (timestamp * 1000);
const years = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24 * 365.25));
const months = Math.floor((differenceInMilliseconds % (1000 * 60 * 60 * 24 * 365.25)) / (1000 * 60 * 60 * 24 * 30));
const days = Math.floor((differenceInMilliseconds % (1000 * 60 * 60 * 24 * 30)) / (1000 * 60 * 60 * 24));
const hours = Math.floor((differenceInMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((differenceInMilliseconds % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((differenceInMilliseconds % (1000 * 60)) / 1000);
if (years > 0) {
return months > 0 ? `${pluralize('year', years)} and ${pluralize('month', months)} ago` : `${pluralize('year', years)} ago`;
} else if (months > 0) {
return `${pluralize('month', months)} and ${pluralize('day', days)} ago`;
} else if (days > 0) {
return `${pluralize('day', days)} and ${pluralize('hour', hours)} ago`;
} else if (hours > 0) {
return `${pluralize('hour', hours)} and ${pluralize('minute', minutes)} ago`;
} else if (minutes > 0) {
return `${pluralize('minute', minutes)} and ${pluralize('second', seconds)} ago`;
} else if (seconds > 30) {
return `${pluralize('second', seconds)} ago`;
} else {
return "just now";
}
}
catch (e) {
console.error("Error in getFormattedTime:", e);
return "[error]";
}
catch (e) {}
};
export default getFormattedTime;