Last active
June 26, 2024 13:21
-
-
Save marcogrcr/9d431ff4dfb5fbb0632f3cf8b415d971 to your computer and use it in GitHub Desktop.
Gets the difference between two dates and a timeline of a series of dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function diffBetweenTwoDates(start, end) { | |
const startTime = new Date(start).valueOf(); | |
const endTime = new Date(end).valueOf(); | |
if (Number.isNaN(startTime)) throw new Error("Invalid start date"); | |
if (Number.isNaN(endTime)) throw new Error("Invalid end date"); | |
const fmt = (value, len = 2) => value.toString().padStart(len, "0"); | |
const diff = new Date(endTime - startTime); | |
const diffNoTime = `${fmt(diff.getUTCFullYear(), 4)}-${fmt(diff.getUTCMonth() + 1)}-${fmt(diff.getUTCDate())}T00:00:00Z`; | |
const days = new Date(diffNoTime).valueOf() / (24 * 3600 * 1000); | |
const dayPart = days > 0 ? `${days}.` : ""; | |
const timePart = `${fmt(diff.getUTCHours())}:${fmt(diff.getUTCMinutes())}:${fmt(diff.getUTCSeconds())}`; | |
return dayPart + timePart; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { diffBetweenTwoDates } from "./diff-between-two-dates"; | |
export function getTimeline(...dates) { | |
const timeline = []; | |
if (dates.length < 2) throw new Error("At least two dates must be specified"); | |
const mDates = dates.map(x => new Date(x)); | |
timeline.push({ | |
date: mDates[0].toISOString(), | |
cSpan: '00:00:00', | |
tSpan: '00:00:00' | |
}); | |
for (let i = 1; i < mDates.length; ++i) { | |
timeline.push({ | |
date: mDates[i].toISOString(), | |
cSpan: diffBetweenTwoDates(mDates[i - 1], mDates[i]), | |
tSpan: diffBetweenTwoDates(mDates[0], mDates[i]) | |
}); | |
} | |
return timeline; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment