fullCalendar v3.9.* dayClick点击返回时间错误问题求助
Let’s get this sorted out—your manual DST workaround shouldn’t be necessary, and we can fix the root cause of the incorrect time being passed to dayClick.
First, let’s break down why this is happening: fullCalendar v3 relies heavily on moment.js (and moment-timezone if you’re using non-local timezones) to handle date/time calculations. If your calendar’s timezone configuration isn’t aligned with your application’s expected timezone, the momentDateFromFullcalendar object will have an offset that doesn’t match your local time—especially when DST is active.
Here are the steps to resolve this properly:
Configure fullCalendar's timezone explicitly
FullCalendar v3 has atimezoneoption that dictates how it handles date conversions. If you’re working with your local system timezone, set it to'local'. If you need a specific timezone (like'Europe/Berlin'), use the IANA timezone ID and make sure you’ve included themoment-timezonelibrary in your project.Example configuration:
$('#calendar').fullCalendar({ // Other calendar options... timezone: 'local', // Replace with your target timezone ID if needed dayClick: function(momentDate) { // No more manual offset hacks needed! logger.debug('clicked on date: ' + momentDate.toDate()); vm.newTermin(momentDate); } });This tells fullCalendar to generate moment objects aligned with your desired timezone, automatically handling DST transitions without manual adjustments.
Verify moment.js and moment-timezone setup
If you’re using a specific timezone (not'local'), ensure you’ve included themoment-timezonelibrary alongside moment.js. FullCalendar v3 requires this to parse and convert timezones correctly. Without it, timezone handling will fall back to UTC, leading to unexpected offsets.Avoid mutating the original moment object
A quick note on your current code: moment objects are mutable, so callingadd()directly onmomentDateFromFullcalendarmodifies the original object. If you ever need to adjust a moment object temporarily, useclone()first (e.g.,momentDateFromFullcalendar.clone().add(-1, 'h')). But with proper timezone configuration, you won’t need this step at all.Debug the raw moment values
If you’re still seeing issues, add some debug logs to inspect the incoming moment object:dayClick: function(momentDate) { console.log('Formatted date:', momentDate.format('YYYY-MM-DD HH:mm:ss Z')); console.log('UTC offset (minutes):', momentDate.utcOffset()); // Your existing code... }This will show you exactly what timezone offset fullCalendar is using, helping you confirm if the
timezoneconfiguration is working as expected.
By setting the correct timezone in fullCalendar, you eliminate the need for manual DST checks and hour adjustments—this is the clean, maintainable fix for your issue.
内容的提问来源于stack exchange,提问作者user1782357

