【发布时间】:2021-11-29 00:29:31
【问题描述】:
我有一个程序,用户可以在其中设置事件,包括开始日期、结束日期和事件重复的重复周期、每周、每月按日期、每月按工作日和每年。用户创建事件后,它会保存在数据库中,并且事件会显示在我的程序主页上的日历中。
到目前为止,我已经能够设计出用于每周、每月按日期和每年重复日期的算法,但不能按工作日重复日期。 “按工作日按月”是指在开始日期和结束日期占据的时间段内,每个月每个工作日重复一次的事件。
例如,在 3 月 1 日和 11 月 1 日之间每个月的第一个星期一重复的事件,3 月 1 日是 3 月的第一个星期一,所以我想生成一个日期是 4 月的第一个星期一,即4 月 5 日,以此类推,从 3 月到 11 月的每个月。
下面的 sn-p 是我按日期每月重复日期的函数,这适用于在开始日期和结束日期之间的任何一个月的 15 日重复的事件。
function repeatEventMonthly(jsonArray, num){
//First I get the start date and end date as strings on a JSON, I separate
//them by the "/" and then use the individual parts to construct two Date Objects
var split = jsonArray[num].Fecha.split("/");
var split2 = jsonArray[num].fechaFin.split("/");
var dd = split[1];
var mm = split[0];
var yy = split[2];
var dd2 = split2[1];
var mm2 = split2[0];
var yy2 = split2[2];
var starDate = new Date();
var endDate = new Date();
starDate.setFullYear(yy);
starDate.setMonth(mm-1);
starDate.setDate(dd);
endDate.setFullYear(yy2);
endDate.setMonth(mm2-1);
endDate.setDate(dd2);
//the variable top means how many days are between the startDate and endDate.
//I use a function that calculates this number
var top = getDaysInDates(starDate, endDate);
if (jsonArray[num].tipoRepeticion == "2") {
//the attribute "tipoRepeticion" in my JSON object lets me know what type of
//repetition the event must be set, 2 means Monthly by Weekday and 3 is Monthly by Date
}else if(jsonArray[num].tipoRepeticion == "3"){
//If the event has repetition type 3, then inside this for loop I generate a new date
//which I create with the value of the startDate and then I add the index number in the for
//loop cycle, meaning that if the startDate is March 3, the in index 1 is March 4, Index 2
//is March 5 and so on, then with an If statement I check that if the date on the
//generated date object is the same as the date of the startDate, I push the date to
//another JSON array that I use to display the dates on the calendar.
for (let index = 0; index < top; index++) {
let sd = new Date(starDate);
sd.setDate(sd.getDate()+index);
if (sd.getDate() == starDate.getDate()) {
let str = ((sd.getMonth()+1) + "/" + sd.getDate() + "/" + sd.getFullYear()).toString();
eventMen.push({
// the function "construcDates" helps me create a valid String for my program
// to display at the user.
date: constructDates(str, 0, jsonArray[num].tipoRepeticion),
title: jsonArray[num].titulo,
descripcion: jsonArray[num].descripcion,
tipo: jsonArray[num].tipo,
tipoRepeticion : jsonArray[num].tipoRepeticion
});
}
}
}
因此,此函数有效地生成相隔一个月但在同一日期的事件,这意味着如果我的事件从 3 月 3 日开始,到 12 月 3 日结束,那么在我的日历中,它会在 4 月 3 日、5 月 3 日、6 月 3 日显示相同的事件,7月3日……一直到11月3日。这个方法可能比我需要的更复杂,但我还在学习 JavaScript,所以这就是我想出的。
然而,尽管已经解决了其他类型重复日期的逻辑,(每周、每月按日期和每年)按工作日每月重复日期变得相当困难,因为在每个月,我不能只总结每个月的 30 或 31 天,并希望日期落在同一个“一个月的第一个星期一”。我想问是否有人对我如何计算这个难题有任何建议或解决方案,还值得指出的是,“任何一个月的第一个星期一”的例子并不是唯一可能的按月重复日期的类型,也是可以是每个月的第二个星期二,也可以是最后一个星期五。
【问题讨论】:
标签: javascript json date