Skip to content

Instantly share code, notes, and snippets.

@JonathonAshworth
Created March 15, 2018 04:00
Show Gist options
  • Save JonathonAshworth/39cee2405bfd072ac818a44c14eb754c to your computer and use it in GitHub Desktop.
Save JonathonAshworth/39cee2405bfd072ac818a44c14eb754c to your computer and use it in GitHub Desktop.
Example of date interval math using Julian day numbers
const fromIso = isoDate => {
const intDiv = (l,r) => ~~(l/r)
const [y, m, d] = isoDate.split('-').map(s => parseInt(s, 10))
return intDiv(1461 * (y + 4800 + intDiv(m - 14, 12)), 4)
+ intDiv(367 * (m - 2 - 12 * intDiv(m - 14, 12)), 12)
- intDiv(3 * intDiv(y + 4900 + intDiv(m - 14, 12), 100), 4)
+ d - 32075
}
const fromIsoInterval = isoInterval =>
isoInterval.split('/').map(fromIso)
const intervalOverlap = (a, b) => !(a[0] > b[1] || a[1] < b[0])
// Assumes overlaps is already checked, will give garbage if no overlap
const intervalIntersection = (a, b) =>
a[0] <= b[0]
? a[1] >= b[1]
? b
: [b[0], a[1]]
: a[1] >= b[1]
? [a[0], b[1]]
: a
// same assumption as intersection
const intervalDifference = (a, b) => {
const ivls = []
const [f,s] = a[0] <= b[0] ? [a,b] : [b,a]
const [l,m] = a[1] >= b[1] ? [a,b] : [b,a]
if (f[0] !== s[0])
ivls.push([f[0], s[0] - 1])
if (l[1] !== m[1])
ivls.push([m[1] + 1, l[1]])
return ivls
}
module.exports = {
fromIso,
fromIsoInterval,
intervalOverlap,
intervalIntersection,
intervalDifference
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment