Files
portfolio/assets/js/dateUtils.js
2025-02-13 08:35:26 +01:00

41 lines
1.1 KiB
JavaScript

function calculateDuration(startDate, endDate) {
const start = new Date(startDate);
const end = endDate ? new Date(endDate) : new Date();
const years = end.getFullYear() - start.getFullYear();
const months = end.getMonth() - start.getMonth();
let totalMonths = years * 12 + months;
if (end.getDate() < start.getDate()) {
totalMonths--;
}
const finalYears = Math.floor(totalMonths / 12);
const finalMonths = totalMonths % 12;
let duration = "";
if (finalYears > 0) {
duration += `${finalYears} year${finalYears > 1 ? "s" : ""}`;
}
if (finalMonths > 0) {
if (duration) duration += " ";
duration += `${finalMonths} month${finalMonths > 1 ? "s" : ""}`;
}
return duration;
}
function formatDateRange(startDate, endDate) {
const start = new Date(startDate);
const end = endDate ? new Date(endDate) : new Date();
const formatDate = (date) => {
return date.toLocaleDateString("en-US", {
month: "short",
year: "numeric",
});
};
const duration = calculateDuration(startDate, endDate);
return `${formatDate(start)} - ${endDate ? formatDate(end) : "Present"} · ${duration}`;
}