Is there any convenient way to do this? Do I really need to write a function for this in…
- User
Is there any convenient way to do this? Do I really need to write a function for this in react native?
Navigate to a quiz tab. Certainly! You can create a utility function in JavaScript that calculates the difference between the current time and a given date and returns a string representing how long ago something happened. Here’s an example of how you might do that in React Native:
First, you can import any necessary libraries for date manipulation, but for simplicity, we’ll avoid external libraries and just use JavaScript’s built-in Date object and basic arithmetic:
// TimeAgo.js const getTimeAgo = (date) => { const now = new Date(); const elapsed = now - new Date(date);
const minutes = Math.floor(elapsed / 60000); const hours = Math.floor(elapsed / 3600000); const days = Math.floor(elapsed / 86400000); const weeks = Math.floor(elapsed / 604800000); const months = Math.floor(elapsed / 2629800000); const years = Math.floor(elapsed / 31557600000);
if (minutes < 1) { return ‘just now’; } else if (minutes < 60) { return {minutes === 1 ? '' : 's'} ago; } else if (hours < 24) { return {hours === 1 ? '' : 's'} ago; } else if (days < 7) { return {days === 1 ? '' : 's'} ago; } else if (weeks < 4) { return {weeks === 1 ? '' : 's'} ago; } else if (months < 12) { return {months === 1 ? '' : 's'} ago; } else { return {years === 1 ? '' : 's'} ago; } };
- Assistant