简体   繁体   中英

Returning to calendar in month view always goes back one month,

I'm having difficulty getting my users to return to the month they were working in after a change is made.

Currently, I have a function that initializes the calendar.

var iv = localStorage.getItem("fcDefaultView") || 'timeGridWeek';
var id = localStorage.getItem("fcDefaultDate") || new Date;
        initialView: iv,
        initialDate: id,
        datesSet: function (dateInfo) {
            localStorage.setItem("fcDefaultView", dateInfo.view.type);
            localStorage.setItem("fcDefaultDate", dateInfo.startStr);
        },

What is strange is that, when the user is in any view other than monthView, everything works fine. But when in monthView, when they return to the calendar, it displays the previous month.

这是因为月份是从 0 开始的,而不是 1。所以一月是“0”,二月是“1”。

The issue you've got with the month view is that the "start" date of any month view in fullCalendar is often a day or two before the start of the month. For example if you open fullCalendar month view for the current month (August 2021) you'll see that the first date displayed on the calendar is 27th July. So if you log dateInfo.startStr as you're adding it to the localStorage, you'll see that for August 2021 (again for example) it'll save 27th July 2021.

However if you then set that as the initial date next time you load the calendar, fullCalendar then sets the view to the month which the date occurs in.

To solve this, rather than using the date provided directly in the datesSet callback, you can get the "currentStart" value from the view object, which is the start of the interval the view is trying to represent, rather than the start of the visible time period. This distinction only really applies in month view, so it has no impact on the already-working behaviour other views.

Change the setItem call to this:

localStorage.setItem("fcDefaultDate", dateInfo.view.currentStart);

As this is a JS Date object which then gets serialised, rather than an ISO string, you need to explicitly parse it when reading it out again, so another small change is required:

var id = Date.parse(localStorage.getItem("fcDefaultDate")) || new Date();

Demo: https://codepen.io/ADyson82/pen/JjNrMBd

Documentation: https://fullcalendar.io/docs/view-object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM