Last active
June 24, 2025 17:32
-
-
Save James-E-A/849acd01187bcf9346bb42231d2f901b to your computer and use it in GitHub Desktop.
Javascript get number of days since start of Gregorian calendar
This file contains hidden or 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
/* | |
* Calculate the number of days since the start of the Gregorian calendar. | |
* @param {Date} [date] - The reference date. Defaults to the current instant. | |
* @param {boolean} [useLocalTime] - Whether to calculate in local time. WARNING: By default, UTC is used; this will, for instance, give a Tuesday result when run at 10pm on a Monday in the United States. | |
* @returns {number} | |
*/ | |
export function gregorianDateInteger(d, useLocalTime) { | |
if (d === undefined) d = new Date(); | |
if (useLocalTime === undefined) useLocalTime = false; | |
// 1. Get timestamp | |
// 2. Apply timezone tweak, if applicable (do this in the integer realm to avoid floating-point edge cases) | |
// 3. Convert to fractional days | |
// 4. Truncate to whole days since 1970-01-01 | |
// 5. Adjust to whole days since 1582-10-14 | |
return Math.floor((d.valueOf() + (useLocalTime ? (d.getTimezoneOffset() * (-1000*60)) : 0)) / (1000*60*60*24)) + 141428; | |
} | |
export default gregorianDateInteger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment