Question

I need to use JavaScript to display the next event on a recurring weekly basis on a website. Let's say we start an event every 10am every Saturday - I'll need it to display that the next event begins on "Saturday, (Month) (Date) at 10am".

The only thing that I need to be dynamic on the website is the date of the next event (both month and date).

Idea 1: One way I started thinking about it I would need to and have some sort of a starting reference calendar date from where the schedule starts, and then some pattern of n-days to calculate the upcoming dates from that starting point and compare those against todays date, then display the result of the next in the sequence

Idea 2: Instead of using a pattern of N-days to calculate from a hard-coded reference point, what if I coded the day of the week the event occurs and check against that, calculating the date by comparing the days of the week and adding to todays date (would have to account for rollovers at 28/30/31 days and a way to account for which months max out at which number)

Maybe I'm way off-base in my thinking, but any help here would be appreciated. I'm learning JavaScript and coming from an HTML+CSS background using jQuery plugins if that helps frame your answer in a way I'll grasp.

Was it helpful?

Solution

Here is a rough solution that may work. It's just general code that you will need to debug but I think it's a good starting point! Date() is a built-in JavaScript object.

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

Please let me know if this helps at all!

OTHER TIPS

You could use rSchedule for this (a javascript recurrence library which I maintain).

Example:

Let's say we start an event every 10am every Saturday

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,
});

The only thing that I need to be dynamic on the website is the date of the next event (both month and date).

// 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...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top