Created
November 28, 2017 18:09
-
-
Save stonetip/5eddc484493cd29c05f27ec17efbae00 to your computer and use it in GitHub Desktop.
Convert a decimal date to either human readable date or UNIX timestamp
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
function leapYear(year) { | |
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0); | |
}; | |
/** | |
* Converts a decimal date, e.g. January 15th 2017 would be 14 / 365 + 2017 = 2017.0384 (days start at 0) | |
* @param decimalDate | |
*/ | |
function convertDecimalDate(decimalDate) { | |
const year = parseInt(decimalDate); | |
const remainder = decimalDate - year; | |
const daysPerYear = leapYear(year) ? 366 : 365; | |
const miliseconds = remainder * daysPerYear * 24 * 60 * 60 * 1000; | |
const yearDate = new Date(year, 0, 1); | |
return new Date(yearDate.getTime() + miliseconds); | |
} | |
const date = convertDecimalDate(2017.90685); | |
console.log(`date: ${date}`); | |
const epochTimestamp = Math.round((new Date(date)).getTime() / 1000); | |
console.log(`epochTimestamp: ${epochTimestamp}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment