unity-calendar/assets/unitymath.js

105 lines
3.1 KiB
JavaScript

const hoursperday = 24
const minutesperhour = 60
const secondsperminute = 60
const secondms = 1000
const minutems = secondms * secondsperminute
const hourms = minutems * minutesperhour
const dayms = hourms * hoursperday
const solaryear = 365.242
const yeardays = 366
const leapchange = -6
const leapyeardays = yeardays + leapchange
const monthdays = 30
const leapfreq = 8
const exleapcyclelength = 800;
const exleapyear = 500;
const exleapyearlowbound = Math.floor(exleapyear / leapfreq) * leapfreq;
const exleapyearupbound = exleapyearlowbound + leapfreq;
const exleapyearlowbounddays = (exleapyearlowbound * yeardays) + ((exleapyearlowbound / leapfreq) * leapchange);
const exleapyearupbounddays = (exleapyearupbound * yeardays) + leapchange + ((exleapyearupbound / leapfreq) * leapchange);
const exleapcycledays = (exleapcyclelength * yeardays) + leapchange + ((exleapcyclelength / leapfreq) * leapchange)
const leapcycledays = (leapfreq * yeardays) + leapchange;
const unityzero = Date.parse("2000-03-08T00:00:00.000Z");
function unixtounity(unixtime) {
const unitytime = unixtime - unityzero;
const days = unitytime / dayms;
const exleapcycles = Math.floor(days / exleapcycledays);
const exleapcycleprogress = days - exleapcycles * exleapcycledays;
let leapcycles;
let leapcycleprogress;
let leapcyclehasex;
if (exleapcycleprogress < exleapyearupbounddays) {
leapcycles = Math.floor(exleapcycleprogress / leapcycledays);
leapcycleprogress = exleapcycleprogress - leapcycles * leapcycledays;
leapcyclehasex = exleapcycleprogress >= exleapyearlowbounddays;
} else {
leapcycles = Math.floor((exleapcycleprogress - leapchange)/ leapcycledays);
leapcycleprogress = (exleapcycleprogress - (leapcycles * leapcycledays)) - leapchange;
leapcyclehasex = false;
}
let leapyearspassed;
if (leapcycleprogress < leapyeardays) {
leapyearspassed = 0;
} else if (!leapcyclehasex || leapcycleprogress < (2 * leapyeardays) + (3 * yeardays)) {
leapyearspassed = 1;
} else {
leapyearspassed = 2;
}
const years = Math.floor((leapcycleprogress - (leapchange * leapyearspassed)) / yeardays);
const yearprogress = leapcycleprogress - ((years * yeardays) + (leapchange * leapyearspassed));
const months = Math.floor(yearprogress / monthdays);
const monthprogress = yearprogress - months * monthdays;
const date = Math.floor(monthprogress);
return `${12000 + (exleapcycles * exleapcyclelength) + (leapcycles * leapfreq) + years}-${months + 1}-${date + 1}`
}
const oldtimes = new Date();
oldtimes.setYear(-600)
console.log(unixtounity(Date.now()))
console.log(unixtounity(oldtimes.getTime()))
console.log(unixtounity(Date.parse("2000-01-01")))
console.log(unixtounity(Date.parse("2000-03-07")))
console.log(unixtounity(Date.parse("2000-03-08")))
console.log(unixtounity(Date.parse("2000-03-09")))
console.log(unixtounity(Date.parse("2001-03-07")))
console.log(unixtounity(Date.parse("3000-03-07")))
console.log(unixtounity(Date.parse("42400-03-07")))