创建自定义日历



我有一个问题,我不知道如何解决它。我需要创建一个日历与我自己的数字。我甚至不知道如何处理这个问题。

这是作业的正文。

在克罗诺斯星球上,庆祝殖民地建立千年,今天是1001年8月24日,星期二。成立纪念日也是在星期二。克罗诺斯历法与地球历法相似:12个月30天,闰年的2月有31天。如果年份的数字是5的倍数,那么年份就是闰年,但是在100的倍数中,只有500的倍数是闰年,例如700、800和900是平年,1000是闰年。有必要编写一个函数来查找任意给定日期在Chronos上的星期几。

我想出了一张闰年的支票。这并不难。

function isLeapYear (year) {
return year%5 === 0 && (0 !== year%100 || year%500 === 0);
} 

但是如何创建日历,创建所有年份的数组,我不确定这个路径是否正确。

let year = {};
for (m=1;m<=12;m++){
year[m] = {};
}
var x = 0;
$.each(year, function(index, value) {
for (d = 1; d<=30; d++){
value[d] = ++x;
if (x === 7){
x = 0;
}
}
});
console.log(year); 

可以这样创建年份吗

我将很高兴得到任何帮助。提前感谢。

我会用不同的方法来解决这个难题,我们可以将1月的第一天定位为一周中的第一天,然后从中扣除其他日期的一周中的一天。

要实现这一点,我们需要一个助手数组来表示一周中的天数:

const daysOfWeek = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
];

以及一些辅助函数:

// Helper method needed to shift arrays in a cyclic way
// We need this to rotate the array above since our reference here is a Tuesday
Array.prototype.rotate = function(count) {
return [...this.slice(count, this.length), ...this.slice(0, count)];
};
// Your helper function :)
function isLeapYear(year) {
return year%5 === 0 && (0 !== year%100 || year%500 === 0);
} 
// Helper function to calculate how many leap years have passed since year 0
function leapYearsUntil(year) {
let c = 0;

for (i = 0; i < year; i++) {
c += isLeapYear(i);
}

return c;
}

基本上,解决方案是找到元年第一天的1月是星期几,然后使用它作为参考计算任何日期的星期几。

function getDayOfWeek(dateString) {
const daysSinceJanTheFirst = 30*12 + 7*30 + 24;
// 1 year (non leap year) + 7 months  + 24 days
const dayJanTheFirst = daysOfWeek.rotate(2).reverse()[daysSinceJanTheFirst % 7];
// We know that '24/08/0001' is a Tuesday
// So we rotate the days of week array by 2 to start counting from Tuesday
// The reverse is needed because we are going back in time   
const daysOfWeekRef = daysOfWeek.rotate(daysOfWeek.indexOf(daysOfWeek) + 2);
// Similarly, now that we know what day is the January the first
// We just fast forward to the day we need to calculate 
const dateArray = dateString.split('/');
const d = parseInt(dateArray[0]);
const m = parseInt(dateArray[1]);
const y = parseInt(dateArray[2]);
const days = d + 30*(m-1) + (isLeapYear(y) * m > 2) + y * 30 * 12 + leapYearsUntil(y);
const dayOfWeek = daysOfWeekRef[days % 7];

console.log(dateString, 'is a', dayOfWeek); // For debug

return dayOfWeek;
}

下面的代码包含js代码和一些断言来测试它:

https://jsfiddle.net/jxmbhup3/(结果显示在控制台中)

最新更新