Recurring Events in FullCalendar

87,487

Solution 1

Simple Repeating Events

To add a simple alternative to those listed here, Fullcalendar now (somewhat) supports weekly recurring events. So if you only need something like: [Every Monday and Thursday from 10:00am to 02:00pm], you can use the following:

events: [{
    title:"My repeating event",
    start: '10:00', // a start time (10am in this example)
    end: '14:00', // an end time (2pm in this example)
    dow: [ 1, 4 ] // Repeat monday and thursday
}],

JSFiddle

This is documented in Background events but it works for regular events as well.

Saving this to a database wouldn't be hard.

Add some restrictions

If you don't want them to repeat infinitely, you would need to add some start and end dates.

So, in the DB:

  • Let the event shown above represent the parent record
  • Have another table with start/end dates.
  • Joined table example:

eventId  timeStart  timeEnd   dow    dateStart      dateEnd
     1      10:00    12:00  [1,4]  2015/03/01   2015/04/01  // Month of March
     1      10:00    12:00  [1,4]  2015/05/01   2015/06/01  // Month of May
     1      10:00    12:00  [1,4]  2016/01/01   2017/01/01  // Year of 2017

Pass this to the client as JSON:

{ id:1, start:"10:00", end:"12:00", dow:[1,4],
  ranges[{start:"2015/03/01", end:"2015/04/01"},
         {start:"2015/05/01", end:"2015/06/01"},
         {start:"2016/01/01", end:"2017/01/01"},]
}

And client side, use fullcalendar's eventRender to only render events when there are within one of the time ranges. Something like this should work:

eventRender: function(event){
    return (event.ranges.filter(function(range){ // test event against all the ranges

        return (event.start.isBefore(range.end) &&
                event.end.isAfter(range.start));

    }).length)>0; //if it isn't in one of the ranges, don't render it (by returning false)
},

That's assuming your events are structured as:

var repeatingEvents = [{
    title:"My repeating event",
    id: 1,
    start: '10:00', 
    end: '14:00', 
    dow: [ 1, 4 ], 
    ranges: [{ //repeating events are only displayed if they are within at least one of the following ranges.
        start: moment().startOf('week'), //next two weeks
        end: moment().endOf('week').add(7,'d'),
    },{
        start: moment('2015-02-01','YYYY-MM-DD'), //all of february
        end: moment('2015-02-01','YYYY-MM-DD').endOf('month'),
    },/*...other ranges*/],
},/*...other repeating events*/];

JSFiddle


Overnight

In case you want overnight repeating events (like here), just go over 24:00 for the end time. For instance:

{
  start: '10:00', //starts at 10 on monday
  end:   '27:00', //24+3 is handled correctly.
  dow: [1]
}

JSFiddle

Solution 2

Take a look at this site... http://fajitanachos.com/Fullcalendar-and-recurring-events/

It offers alot of good insite on recurring events. FullCalendar does support recurring events in respect to the id. You can handle the events either server side or client side, but the preference would be server side. I will give you some ideas, but its not all inclusive. As I have learned recurring events are a pain to maintain.

If you wanted to handle them client side, you would have to loop through the frequency of the repeating event and the logic of which days. You would probably need to use the eventRender callback, then render each looped event using the options callback. The problem with this will be that you still have to save the recurring frequency and a logical operator for your frequency option in your database...

(column1:frequency=(int)8, column2:type=enum(a'b'c), a=daily, b=weekly, c=monthly etc).

...and then anytime you edited that event it would edit all of the events. If you needed delete just one event you would run into a series of issues within your logic and it could easily become a GIANT mess.

The second option was to do all this server side. Creating two tables, one with the parent event, and the second with all its recurrences. In the parent table you would store the general information, such as a unique id, color, background color, title, allDay, isRecurring, frequency, type etc. In the child table, you would use the unique id from the parent table to associate each recurrence (keep in mind if you want to delete/edit individual events the child table rows need to have their own unique id as well and a column that labels which table it is located). When you add a recurring event, you need to add a enum field that labels whether or not it is a recurring event or not AKA...

column:recurring=enum('0','1')---true/false

... and then you need to add each recurrence, into the child table with its specific information like start and end etc. When you query the event you could either query from the parent and then if the event is recurring get those events associated in a second query, or you could use an INNER JOIN on table1.id=table2.parentID in one single query.

As you can see, recurring event can get very detailed very fast, find out what logic you need and I hope this helps you or someone at least get started. Cheers.

Solution 3

No need to make parent and child relationship here is the code that provide simple solution for recurring events in jquery Full calender use these below functions in your php file that you use further to call all your events.

function render_fccalendar_events() {
        $_POST['start'] = strtotime('2013-05-01');
        $_POST['end'] = strtotime('2013-05-31');
        $start = date('Y-m-d',$_POST['start']);
        $end = date('Y-m-d', $_POST['end']);
        $readonly = (isset($_POST['readonly'])) ? true : false;    
        $events = fcdb_query_events($start, $end);       
        render_json(process_events($events, $start, $end, $readonly));
}

function process_events($events, $start, $end, $readonly) {
    if ($events) {
        $output = array();
        foreach ($events as $event) {
            $event->view_start = $start;
            $event->view_end = $end;
            $event = process_event($event, $readonly, true);
            if (is_array($event)) {
                foreach ($event as $repeat) {
                    array_push($output, $repeat);
                }
            } else {
                array_push($output, $event);
            }
        }
        return $output;
    }
}

function process_event($input, $readonly = false, $queue = false) {
    $output = array();
    if ($repeats = generate_repeating_event($input)) {
        foreach ($repeats as $repeat) {
            array_push($output, generate_event($repeat));
        }
    } else {
        array_push($output, generate_event($input));
    }

    if ($queue) {
        return $output;
    }
    render_json($output);
}


function generate_event($input) {
    $output = array(
        'id' => $input->id,
        'title' => $input->name,
        'start' => $input->start_date,
        'end' => $input->end_date,
        'allDay' => ($input->allDay) ? true : false,
        //'className' => "cat{$repeats}",
        'editable' => true,
        'repeat_i' => $input->repeat_int,
        'repeat_f' => $input->repeat_freq,
        'repeat_e' => $input->repeat_end
    );
    return $output;
}



function generate_repeating_event($event) {

    $repeat_desk = json_decode($event->repeat_desk);
    if ($event->repeat == "daily") {
        $event->repeat_int =0;
        $event->repeat_freq = $repeat_desk->every_day;
    }
    if ($event->repeat == "monthly") {
        $event->repeat_int =2;        
        $event->repeat_freq = $repeat_desk->every_month;
    }
    if ($event->repeat == "weekly") {
        $event->repeat_int =1;                
       $event->repeat_freq = $repeat_desk->every_weak;
    }
    if ($event->repeat == "year") {
        $event->repeat_int =3;                        
        $event->repeat_freq = $repeat_desk->every_year;
    }

    if ($event->occurrence == "after-no-of-occurrences") {
        if($event->repeat_int == 0){
            $ext = "days";
        }
        if($event->repeat_int == 1){
            $ext = "weeks";
        }
        if($event->repeat_int == 2){
            $ext = "months";
        }
        if($event->repeat_int == 3){
            $ext = "years";
        }
       $event->repeat_end =  date('Y-m-d',strtotime("+" . $event->repeat_int . " ".$ext));
    } else if ($event->occurrence == "no-end-date") {
        $event->repeat_end = "2023-04-13";
    } else if ($event->occurrence == "end-by-end-date") {
        $event->repeat_end = $event->end_date;
    }



    if ($event->repeat_freq) {

        $event_start = strtotime($event->start_date);
        $event_end = strtotime($event->end_date);
        $repeat_end = strtotime($event->repeat_end) + 86400;
        $view_start = strtotime($event->view_start);
        $view_end = strtotime($event->view_end);
        $repeats = array();

        while ($event_start < $repeat_end) {
            if ($event_start >= $view_start && $event_start <= $view_end) {
                $event = clone $event; // clone event details and override dates
                $event->start_date = date(AEC_DB_DATETIME_FORMAT, $event_start);
                $event->end_date = date(AEC_DB_DATETIME_FORMAT, $event_end);
                array_push($repeats, $event);
            }
            $event_start = get_next_date($event_start, $event->repeat_freq, $event->repeat_int);
            $event_end = get_next_date($event_end, $event->repeat_freq, $event->repeat_int);
        }
        return $repeats;
    }
    return false;
 }

function get_next_date($date, $freq, $int) {
    if ($int == 0)
        return strtotime("+" . $freq . " days", $date);
    if ($int == 1)
        return strtotime("+" . $freq . " weeks", $date);
    if ($int == 2)
        return get_next_month($date, $freq);
    if ($int == 3)
        return get_next_year($date, $freq);
}

function get_next_month($date, $n = 1) {
    $newDate = strtotime("+{$n} months", $date);
    // adjustment for events that repeat on the 29th, 30th and 31st of a month
    if (date('j', $date) !== (date('j', $newDate))) {
        $newDate = strtotime("+" . $n + 1 . " months", $date);
    }
    return $newDate;
}

function get_next_year($date, $n = 1) {
    $newDate = strtotime("+{$n} years", $date);
    // adjustment for events that repeat on february 29th
    if (date('j', $date) !== (date('j', $newDate))) {
        $newDate = strtotime("+" . $n + 3 . " years", $date);
    }
    return $newDate;
}

function render_json($output) {
    header("Content-Type: application/json");
    echo json_encode(cleanse_output($output));
    exit;
}


function cleanse_output($output) {
    if (is_array($output)) {
        array_walk_recursive($output, create_function('&$val', '$val = trim(stripslashes($val));'));
    } else {
        $output = stripslashes($output);
    }
    return $output;
}

function fcdb_query_events($start, $end) {
    global $wpdb;
    $limit = ($limit) ? " LIMIT {$limit}" : "";
    $result = $wpdb->get_results("SELECT id, name,start_date,end_date,repeat_desk,`repeat`,occurrence,occurrence_desk

                                        FROM " . 

$wpdb->prefix . "lgc_events
                                        WHERE (
                                        (start_date >= '{$start}' AND start_date < '{$end}')
                                        OR (end_date >= '{$start}' AND end_date < '{$end}')
                                        OR (start_date <= '{$start}' AND end_date >= '{$end}')
                                        OR (start_date < '{$end}' AND (`repeat`!= ''))


                            )
                                        ORDER BY start_date{$limit};");

    return return_result($result);
}


function return_result($result) {
    if ($result === false) {
        global $wpdb;
        $this->log($wpdb->print_error());
        return false;
    }
    return $result;
}

in the above code i used repeat_desk in which i store json code for repeat frequencyenter image description here

and jquery to call your file

 events:  {
                url: '<?php echo $lgc_plugindir; ?>includes/imagerotator.php',
                data: {
                    action: 'get_events'
                },
                type: 'POST'
            }

i used this for wordpress you can use this code as per your requirement

Solution 4

For people who have more complex recurring events than what FullCalendar can handle builtin (see slicedtoad's answer), you can use rSchedule.

For example, Monday only to time 7:00AM to 9:00 AM, tuesdays - 4:00PM to 9:00PM

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

const mondayDate = new Date(2019, 6, 15);
const tuesdayDate = new Date(2019, 6, 16);

const schedule = new Schedule({
  // add specific dates
  dates: [
    new StandardDateAdapter(mondayDate, {duration: 1000 * 60 * 60 * 2})
  ],
  // add recurrence rules
  rrules: [{
    start: tuesdayDate,
    duration: 1000 * 60 * 60 * 5, // duration is expressed in milliseconds
    frequency: 'WEEKLY'
  }],
});

const firstFiveEvents = schedule
  .occurrences({ take: 5 })
  .toArray()
  .map(adapter => 
    ({title: 'My event title', start: adapter.date, end: adapter.end})
  );

// You can then pass `firstFiveEvents` to fullcalendar for rendering

rSchedule also supports moment / luxon, as well as timezones. For more information, you can check out the rSchedule docs.

Solution 5

This seemed to work quite nicely within the eventRender: function(event, element){}

            EXAMPLE JSON:
            var json = [{title: "All Day Event",
              start: "2015-12-22T00:00",
              end: "2015-12-22T23:55",
              dow: [2,4],
              recurstart: moment("2015-12-22").startOf("week"),
              recurend: moment("2015-12-22").endOf("week").add(1,'w')},{
              title: "Long Event",
              start: "2015-12-21T00:00",
              end: "2015-12-24T23:55",
              recurstart: moment("2015-12-21").startOf("month"),
              recurend: moment("2015-12-24").endOf("month"),
            }];

            eventRender: function(event, element){
            var theDate = moment(event.start).format("YYYY-MM-DD");
            var startDate = event.recurstart;
            var endDate = event.recurend;

            if (startDate < theDate && theDate < endDate) {
                console.log(theDate);
                }
            else {
                return event.length>0;
            }
            }, /* End eventRender */

1) Set a Start/End date & time in the JSON.

2) Create two custom recur Start and recur Ends in the JSON.

3) Use moment.js to create the recur durations: http://momentjs.com/docs/#/durations/.

4) Recur Start uses the (start:) date to pinpoint the start of the week.

5) Recur End uses (end:) date to pinpoint the end of the week + adding 1 week.

6) Adding 1, 2, 3 weeks can create the recur limit.

7) Adding another part of the JSON called (recurlimit:"") could manage the recur limit.

8) Using variables within the eventRender - set the date my example uses (theDate) which is moment(event.start). It's important to format this correctly so that the start/ end/ recurstart etc all match formats i.e (YYYY-MM-DD) http://momentjs.com/docs/#/displaying/format/.

9) Variable for the custom recurstart

10) Variable for the custom recurend

11) Use an IF statement to see weather the (theDate) falls between (recurstart) & (recurend) - log result

12) Use ELSE statement to return the length>0 to hide other events that don't fall within that parameter.

13) Non recurring events must have moment("match start date").startOf("month") & moment("match start date").endOf("month") otherwise they won't be visible.

Share:
87,487
Junnel Gallemaso
Author by

Junnel Gallemaso

Updated on July 09, 2022

Comments

  • Junnel Gallemaso
    Junnel Gallemaso almost 2 years

    I am using jQuery FullCalendar as my calendar used in my website for availability agenda.

    Is there any functions/methods/options in fullcalendar that handles my recurring events by Days? For example, Monday only to time 7:00AM to 9:00 AM, tuesdays - 4:00PM to 9:00PM, something like that?

  • Ron E
    Ron E almost 11 years
    For more information on implementing recurring events on the server side also check out this link, it looks like the author of the first link used this info to create his tables: martinfowler.com/apsupp/recurring.pdf
  • Enrique
    Enrique almost 10 years
    Do you know a library or php code which could help me to save the recurrent events in the child table? Eg. From Thursday Jul, 17th, every Thursday from 10:00 to 11:00 until Thursday Nov. 20.... it would be about 19 records... thanks
  • Juan Gonzales
    Juan Gonzales almost 10 years
    Honestly I don't know of any libraries, and the code I use for recurring events is quite complex and probably wouldn't do you any good. Check out the link I left and start from there. If you know how many occurrences there will be that just use an input field and then input the event that amount of times into your child table.
  • Timber
    Timber about 9 years
    Thanks! This is helpful, but could spill more details on the ranges and eventRender? I could figure get it to render them within the time ranges.
  • Timber
    Timber about 9 years
    Thank you so much for adding that! It worked. Big hugs. OP should mark this the answer :).
  • DanielST
    DanielST about 9 years
    @TimothyOnggowasito It's a good solution if your events are weekly based. But if you need something like monthly or 10 day cycles, you need something a bit more complex.
  • Surt
    Surt almost 9 years
    That's great. It gives more insight to the way fullcalendar works. Thank you a lot!
  • Deepanshu Goyal
    Deepanshu Goyal almost 9 years
    The answer works perfect... Thanks. I am trying to display the recurring event, but Need to remove it for a specific date, suppose I have a recurring event for all Sunday, but I need to remove the event for a specific Sunday only
  • DanielST
    DanielST almost 9 years
    @Deepanshu Just add another table called "excludedDates" so you have a list of exceptions for every range. Then in eventRender, check that the event you are rendering is not in that list. Let me know if that's clear.
  • Deepanshu Goyal
    Deepanshu Goyal over 8 years
    @slicedtoad Thanks for the reply, Can I disable specific dates in fullcalendar or a date range
  • DanielST
    DanielST over 8 years
    @deepanshu either. ‘excludedDates‘ could have singles dates or start and end dates.
  • Neil Masson
    Neil Masson over 8 years
    Answers are better if they include an explanation as well as code.
  • tohood87
    tohood87 over 8 years
    Apologies its my first stackoverflow post. I have added a little more info to hopefully make it a little clearer.
  • Sudarshan Kalebere
    Sudarshan Kalebere almost 8 years
    @slicedtoad please have a look at this question sir stackoverflow.com/questions/37204410/…
  • Rahul Pawar
    Rahul Pawar almost 8 years
    recuring not working for me...plz help me and simple dow: [ 1, 4 ] also not working.
  • bipin patel
    bipin patel about 7 years
    Nice example.but if i have display event repeat every month only first sunday than what i do?
  • Michael
    Michael about 7 years
    Very nice solution. @slicedtoad For the exceptions option, if I have my excludedDates table listed in a json string, how can I check if event.start in not a date in this list in the event render?
  • Kevin Cohen
    Kevin Cohen about 7 years
    Is there a way to show recurring events FROM a certain date range? Like I want to show recurring events starting from today. I dont want the calendar to have the recurring events of the past week, month etc
  • DanielST
    DanielST about 7 years
    @KevinCohen sure, just add another condition to the eventRender function. This answer is a template to show how to conditionally render events, the actual conditions you use are flexible.
  • ADyson
    ADyson over 6 years
    it's not clear how this would be integrated with fullCalendar in order to do with the question asks. On its own it doesn't create a format whereby recurrence can be specified to the calendar, nor does it provide any code by which to manipulate the events feed in order to create recurrence. And just providing a link and no further info is a poor answer. Links can go stale.
  • Gabriel Glenn
    Gabriel Glenn over 6 years
    Beware that selectOverlap:false behavior will not be the one expected : it will prevent any overlap of event on the time slot, even if renderEvents logic disabled this event and the time slot is free. Check the scheduler issue github.com/fullcalendar/fullcalendar-scheduler/issues/345
  • Aaron R.
    Aaron R. about 6 years
    Thanks, this was great, once I wrapped my head around it. I added if (event.hasOwnProperty('ranges')) { in my case for the eventRender because I didn't want to have to add the ranges property for all my one-time dates.
  • Sukhjinder Singh
    Sukhjinder Singh over 5 years
    @slicedtoad is it possible to removed indivisual event from ranges. For example I created repeating events...ie every Monday. if the Nov 5th is a holiday, then event should not be happend on that day. Can remove event from ranges for Nov 5th?
  • Ken Ramirez
    Ken Ramirez about 5 years
    Thank you! is there a way to drag and drop it? i can the normal events but not the repeatings one
  • Paula Livingstone
    Paula Livingstone about 5 years
    That link you posted at the start of your post is dead. Do you happen to have any updated info about resources for this package relating to recurring events?
  • ADyson
    ADyson almost 5 years
    how would this be integrated with fullCalendar, to display the events, then? It's not really clear from your answer.
  • John
    John almost 5 years
    @ADyson I only have experience using the Angular FullCalendar component, but you simply map occurrences to the event format fullcalendar expects, and pass them to fullcalendar for rendering. A simple example: schedule.occurrences({ take: 5 }).toArray().map(adapter => ({title: 'My event title', start: adapter.date, end: adapter.end}))
  • ADyson
    ADyson almost 5 years
    If you make this part of the answer text itself, it's worth an upvote - thanks!
  • John
    John almost 5 years
    I fleshed out the example 👍
  • Jordan_Walters
    Jordan_Walters over 2 years
    Nitesh, I am keep getting the following error when trying to use your snippet: Uncaught TypeError: Cannot read property 'length' of undefined Any ideas? Do you have a codepen of this working by chance? This is definitely what I am looking to do and any advice you have would be most helpful.
  • Nitesh S Chauhan
    Nitesh S Chauhan over 2 years
    Hello @Jordan_Walters , You can define length in event click function like below code: arg.length = '10'; I hope it will be helpful.