Get the first and last visible date of the fullcalendar without using datepicker

518 views Asked by At

I use fullcalendar in my code and have implemented and added events into it, but my goal was to get the first visible and last visible date of the calendar.

What we wanted to do is get the visible first and last dates so that we'll be able to throw the extracted dates in the database and get all events within that range of dates.

I've tried this Get the start and end dates visible in a datepicker days view? but I want to use jQuery and fullCalendar only. Is there other way to extract the dates without using datepicker?

enter image description here

2

There are 2 answers

6
fdomn-m On BEST ANSWER

Using version 5.5.1, you can inspect the rendered HTML. The day cells have class fc-daygrid-day and data-date="{date}"

Given the original div id is "calendar" you can use:

var cells = $("#calendar td.fc-daygrid-day");
console.log(cells.length, cells.first().data("date"), cells.last().data("date"))

Example snippet:

$(function() { 
  var calendarEl = document.getElementById('calendar');
  var calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: 'dayGridMonth'
  });
  calendar.render();
  
  var cells = $("#calendar td.fc-daygrid-day");
  console.log(cells.length, cells.first().data("date"), cells.last().data("date"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/main.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/main.css">

<div id='calendar'></div>

6
ADyson On

Is it possible to get the first date of the first week and last date of the last week of the fullcalendar

...yes easily - in the latest version (v5 at the time of writing) you can just ask for the current view and it has properties which contain those dates.

However, you also said this was

so that we'll be able to throw the extracted dates in the database and get all events within that range of dates.

There's no reason for you to do this manually, if that's your purpose. FullCalendar already provides ways of specifying the source of your events - you can either simply point it at a URL which returns JSON in the fullCalendar events format, or if you need more flexibility, you can define a callback function where you can use custom code to fetch the events from their source.

The key thing about both those approaches is that fullcalendar automatically

  • calls the URL / runs the function every time the date range changes on the calendar, and

  • provides you with the start and end dates of the new date range, so that your server can filter the events it returns to be only ones which fall within that range.

There's no need for you to spend time manually attempting to extract date ranges from the calendar or feed it events by other methods.