Here's a step-by-step implementation of the required logic to calculate the time difference between a given post date and the current date and time in plain JavaScript:
JavaScript Function Implementation
function timeAgo(postDateString) {
const postDate = new Date(postDateString); // Convert input date string to Date object
const currentDate = new Date(); // Get the current date and time
// Calculate the difference in milliseconds
const differenceInMilliseconds = currentDate - postDate;
// Define time constants in milliseconds
const oneMinute = 60 * 1000; // 60 seconds
const oneHour = 60 * oneMinute; // 60 minutes
const oneDay = 24 * oneHour; // 24 hours
const oneMonth = 30 * oneDay; // Approximate 30 days
const oneYear = 12 * oneMonth; // 12 months
// Calculate the time difference and return appropriate string
if (differenceInMilliseconds < oneMinute) {
return "just now";
} else if (differenceInMilliseconds < oneHour) {
const minutes = Math.floor(differenceInMilliseconds / oneMinute);
return `${minutes} minute${minutes > 1 ? "s" : ""} ago`;
} else if (differenceInMilliseconds < oneDay) {
const hours = Math.floor(differenceInMilliseconds / oneHour);
return `${hours} hour${hours > 1 ? "s" : ""} ago`;
} else if (differenceInMilliseconds < oneMonth) {
const days = Math.floor(differenceInMilliseconds / oneDay);
return `${days} day${days > 1 ? "s" : ""} ago`;
} else if (differenceInMilliseconds < oneYear) {
const months = Math.floor(differenceInMilliseconds / oneMonth);
return `${months} month${months > 1 ? "s" : ""} ago`;
} else {
const years = Math.floor(differenceInMilliseconds / oneYear);
return `${years} year${years > 1 ? "s" : ""} ago`;
}
}
// Example Usage
console.log(timeAgo("2024-12-09T02:47:05.389Z")); // Output depends on the current date and time
Explanation
-
Input Parsing:
- Convert the given date string into a JavaScript
Date
object. - Get the current date and time using
new Date()
.
- Convert the given date string into a JavaScript
-
Time Difference Calculation:
- Subtract the
postDate
from thecurrentDate
to get the difference in milliseconds.
- Subtract the
-
Define Time Constants:
- Use constants for one minute, one hour, one day, one month, and one year in milliseconds for easier calculations.
-
Conditional Checks:
- Check the time difference against these constants to determine the appropriate time period.
- Format the output string with proper pluralization (e.g., "1 minute" vs. "2 minutes").
-
Return Result:
- Return a human-readable string like "20 minutes ago," "1 day ago," etc., based on the calculated time difference.
This function is easy to use and handles the most common cases efficiently.