jan*_*mon 4 html javascript google-calendar-api
Google 在 GoogleCalendar HTML 中的每一天使用唯一的 DateKeys,例如
<div
data-datekey="129"
role="gridcell"
tabindex="-1"
jsname="RjPD4e"
aria-labelledby="tsc-0"
data-column-index="0"
data-principal-ids="amFuLm5pY2tsYXNAbmFtaWNzLmNvbQ"
class="YvjgZe Qbfsob">
Run Code Online (Sandbox Code Playgroud)
是否有任何公式可以计算给定日期键的日期?
看起来 代表了dateKey从那时起1.1.1970以针对字节移位优化的格式。
一年有2^9(512)天。一个月有2^5(32)天。
要计算 ,您datekey需要01.01.1970计算:
0年(自 1970 年起)* 512
+ 1月* 32
+ 1日
= 33
要计算 ,您datekey需要01.01.2000计算:
30年(自 1970 年起)* 512
+ 1月* 32
+ 1日
= 15393
要计算给定日期键的日期,您可以执行相反的操作。模计算可能如下所示:
function getDate(dateKey) {
const yearOffset = (dateKey - 32) % 512;
const year = (dateKey - 32 - yearOffset) / 512;
const day = yearOffset % 32;
const month = (yearOffset - day) / 32;
return new Date(year + 1970, month, day);
}
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么他们会想出这样的逻辑?
回应 @jantimon 的回答:我猜他们必须对日期进行大量计算,并希望它高效。
奇怪的是,如果您查看侧边栏中的小日历,data-datekey它不会使用属性,而是使用data-date格式YYYYMMDD。
无论如何,我使用按位运算重写了您的转换函数,因为这样更容易阅读。
function datekeyToDate(key) {
/* # BITS: [year_rel(6)][month(4)][day(5)] */
const day = key & 0b11111;
const month = (key>>5) & 0b1111;
const year_rel = (key>>9);
const year = 1970 + year_rel;
return new Date(year, month, day);
}
function dateToDatekey(date) {
const y = date.getFullYear() - 1970;
const m = date.getMonth()+1; /* getMonth() returns 0-based index */
const d = date.getDate();
return (y<<9) + (m<<5) + d;
}
Run Code Online (Sandbox Code Playgroud)