Standalone JavaScript to calculate elapsed time from a date
To dynamically show my age and years of sobriety for my now page, I needed a simple way to calculate years, months, and days since a given date and time.
This lightweight JavaScript snippet calculates how much time has elapsed since a given date and returns a nicely formatted, human-readable string like “2 years, 3 months, and 12 days.” It does this with native Date
methods, without any external dependencies like date-fns
. Here’s how it works.
Script
function pluralize(value, unit) {
return value === 1 ? `${value} ${unit}` : `${value} ${unit}s`;
}
function getDuration(startDateInput, endDateInput = new Date()) {
const startDate = new Date(startDateInput);
const endDate = new Date(endDateInput);
let start = new Date(startDate);
let end = new Date(endDate);
if (end < start) [start, end] = [end, start];
let years = end.getFullYear() - start.getFullYear();
let months = end.getMonth() - start.getMonth();
let days = end.getDate() - start.getDate();
if (days < 0) {
const prevMonth = new Date(end.getFullYear(), end.getMonth(), 0);
days += prevMonth.getDate();
months--;
}
if (months < 0) {
months += 12;
years--;
}
const parts = [];
if (years > 0) parts.push(pluralize(years, "year"));
if (months > 0) parts.push(pluralize(months, "month"));
if (days > 0) parts.push(pluralize(days, "day"));
if (parts.length === 0) return "0 days";
if (parts.length === 1) return parts[0];
if (parts.length === 2) return `${parts[0]} and ${parts[1]}`;
const lastPart = parts.pop();
return `${parts.join(", ")}, and ${lastPart}`;
}
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll(".duration[data-start]").forEach(el => {
const start = el.getAttribute("data-start");
if (start) {
el.textContent = getDuration(start);
}
});
});
Usage example
The script is designed to be used inline with other HTML or Markdown text content, within a <span>
tag and with a placeholder in the event the script fails or is delayed in executing.
<span class="duration" data-start="1991-07-26T13:44:00Z">...</span>
You’ll then just need to import the script on the target page, either pasted with an inline <script>
tag or referenced as src
.
<script src="/path/to/script.js"></script>
Live demo
Try it out! Select a date below to see a live-calculated duration:
Hope this little utility is helpful for somebody. Let me know if you use this in a project, or if you’d like a version that supports relative time (“2 years ago”) or custom formatting.