Skip to content

Instantly share code, notes, and snippets.

@zazaulola
Created October 7, 2024 11:25
Show Gist options
  • Save zazaulola/da1fe71e1e430472e823a21ddef71c02 to your computer and use it in GitHub Desktop.
Save zazaulola/da1fe71e1e430472e823a21ddef71c02 to your computer and use it in GitHub Desktop.
Some calendar functions
// calculate week number for date
function calcWN(y, m, d) {
let J = gc2jd(y, m, d);
let d4 = (J + 31741 - J % 7) % 146097 % 36524 % 1461;
let L = 0 | d4 / 1460;
let d1 = (d4 - L) % 365 + L;
return (0 | d1 / 7) + 1;
}
// calculate week day for date
// 0 - sunday, 6 - saturday
function calcWD(y, m, d){
return (d += m < 3 ? y-- : y - 2, (0 | 23 * m / 9) + d + 4 + (0 | y / 4) - (0 | y / 100) + (0 | y / 400)) % 7;
}
// convert date to julian day
function gc2jd(y, m, d) {
[y, m] = m < 3 ? [y - 1, m + 12] :[y, m];
return 2 - (0 | y / 100) + (0 | y / 400) + d + (0 | 365.25 * (y + 4716)) + (0 | 30.6001 * (m + 1)) - 1524;
}
// convert julian day to date
function jd2gc(J) {
let A = J + 32044;
let B = (0 | (4 * A + 3) / 146097);
let C = A - (0 | (B * 146097) / 4);
let D = (0 | (4 * C + 3) / 1461);
let E = C - (0 | (1461 * D) / 4);
let M = (0 | (5 * E + 2) / 153);
let day = E - (0 | (153 * M + 2) / 5) + 1;
let month = M + 3 - 12 * (0 | (M / 10));
let year = B * 100 + D - 4800 + (0 | (M / 10));
return { year, month, day };
}
// time shift for julian day
function time2jt(hours, min, sec, tz) {
let pds = 864e2;
return ((hours - tz) * 3600 + min * 60 + sec) / pds;
}
// convert timestamp (in seconds) to julian day
function ts2jd(ts) {
let origin = 2440587.5;
let pds = 864e2;
return origin + (ts / pds);
}
// convert julian day to timestamp (in seconds)
function jd2ts(jd) {
let origin = 2440587.5;
let pds = 864e2;
return (jd - origin) * pds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment