Skip to content

Instantly share code, notes, and snippets.

@stonetip
Created November 28, 2017 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stonetip/5eddc484493cd29c05f27ec17efbae00 to your computer and use it in GitHub Desktop.
Save stonetip/5eddc484493cd29c05f27ec17efbae00 to your computer and use it in GitHub Desktop.
Convert a decimal date to either human readable date or UNIX timestamp
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