Skip to content

Commit

Permalink
fix: date math lol
Browse files Browse the repository at this point in the history
  • Loading branch information
kiosion committed Jan 25, 2024
1 parent fb1c634 commit 1d6aecb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 25 deletions.
13 changes: 5 additions & 8 deletions svelte-app/src/components/about/timeline-section.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,17 @@
export let section: WorkTimelineItem[];
const title = section[0].title,
totalRange = {
start: section[section.length - 1].range.start,
end: section[0].range.end
};
const title = section[0].title;
</script>

<section>
<div>
<h2>{title}</h2>
<p>
{$displayRange(totalRange.start, totalRange.end)} &bull; {$displayMonthDuration(
totalRange.start,
totalRange.end
{$displayRange(section[section.length - 1].range.start, section[0].range.end)} &bull;
{$displayMonthDuration(
section[section.length - 1].range.start,
section[0].range.end
)}
</p>
</div>
Expand Down
30 changes: 13 additions & 17 deletions svelte-app/src/lib/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,21 @@ export const displayMonthDuration = derived<
}

const start = new Date(startDate),
end = endDate ? new Date(endDate) : new Date();
end = endDate ? new Date(endDate) : new Date(),
diffMs = end.getTime() - start.getTime(),
diffDays = Math.floor(diffMs / 86400000),
diffMonths = Math.floor(diffDays / 30);

let years = end.getFullYear() - start.getFullYear();
let months = end.getMonth() - start.getMonth();
if (diffMonths === 0 || diffMonths === 1) {
return t('{month} month', { month: 1 });
}

// Adjust for cases where the end month is earlier in the year than the start month
if (months < 0) {
years--;
months += 12; // Add the months that have passed in the current year
if (diffMonths < 12) {
return t('{month} months', { month: diffMonths });
}

// Consolidate total duration into years and months
years += Math.floor(months / 12);
months %= 12;
const years = Math.floor(diffMonths / 12),
months = diffMonths % 12;

let yearString = '',
monthString = '';
Expand All @@ -61,23 +62,18 @@ export const displayMonthDuration = derived<
if (years === 1) {
yearString = t('{year} year', { year: years });
} else {
yearString = t('{year} years', { year: years });
yearString = t('{years} years', { years });
}
}

if (months > 0) {
if (months === 1) {
monthString = t('{month} month', { month: months });
} else {
monthString = t('{month} months', { month: months });
monthString = t('{months} months', { months });
}
}

// Handle the case where the difference is less than one month
if (years > 0 && months > 0) {
monthString = t('{month} month', { month: 1 });
}

return `${yearString}${yearString && monthString ? ' ' : ''}${monthString}`;
};
});

0 comments on commit 1d6aecb

Please sign in to comment.