如何使用JavaScript在计划中显示下一个每周重复日期?

时间:2013-09-27 17:39:23

标签: javascript date calendar schedule recurring

我需要使用JavaScript在网站上每周定期显示下一个事件。假设我们每周六上午10点开始一个活动 - 我需要它来显示下一个活动开始于“星期六,(Month)(Date)上午10点”。

我在网站上唯一需要动态的是下一个活动的日期(monthdate)。

想法1:我开始考虑这个问题的一种方法我需要并且有一些从日程安排开始的某个起始参考日历日期,然后是一些n天计算模式从该起点开始的即将到来的日期,并将这些日期与今天的日期进行比较,然后在序列中显示下一个的结果

想法2:如果我使用N-days模式从硬编码参考点进行计算,如果我对事件发生的星期几进行编码并对此进行检查,那么计算通过比较一周中的天数和添加到今天的日期(必须考虑到28/30/31天的翻转以及考虑哪个月的最大数量来计算日期)的日期

也许我的想法偏离了基础,但是在这里任何帮助都会受到赞赏。我正在学习JavaScript,并使用jQuery插件来自HTML + CSS背景,如果这有助于以我将要掌握的方式构建您的答案。

2 个答案:

答案 0 :(得分:1)

这是一个可行的粗略解决方案。这只是您需要调试的通用代码,但我认为这是一个很好的起点! Date()是一个内置的JavaScript对象。

var today = new Date();
//var dd = today.getDate();    *just some sample functions of Date()*
//var mm = today.getMonth()+1; *January is 0!*

if(today.getDay() == 6) alert('it is saturday');
// today.getDate() < 8   *this can be used to check where in the month a day falls
// if you want only first, second, third, etc., Saturday

如果这有帮助,请告诉我!

答案 1 :(得分:0)

您可以为此使用rSchedule(我维护的javascript递归库)。

示例:

  

假设我们每个星期六的上午10点开始活动

import { Schedule } from '@rschedule/rschedule';
import { StandardDateAdapter } from '@rschedule/standard-date-adapter';

const schedule = new Schedule({
  rrules: [{
    frequency: 'WEEKLY',
    // the hypothetical start datetime of your recurring event
    start: new Date(2019, 5, 15, 10),
  }],
  dateAdapter: StandardDateAdapter,
});
  

我唯一需要在网站上保持动态的是下一个事件的日期(月份和日期)。

// get standard javascript iterator for occurrences starting after now
const iterator = schedule.occurrences({
  start: new Date()
})

// the next date
const nextDate = iterator.next().value;

// or iterate over all future occurrences
for (const date of iterator) {
  // do stuff...
}