You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重置bootstrap-datepicker的月份与年份?

Resetting Month/Year Selection in bootstrap-datepicker

Great question! I’ve dealt with this exact scenario when working with bootstrap-datepicker, so let’s break down the solutions based on how your picker is set up:

1. For Month/Year-Only Pickers

If you’ve configured your picker to only let users select months and years (e.g., using minViewMode: 1 or a date format like "yyyy-mm"), the cleanest way to clear the selected values is to use the official setDate API with null, then sync the UI with update:

$('#datepicker').datepicker('setDate', null).datepicker('update');

This will empty the input field and reset the picker’s dropdown view back to the default (usually the current month and year).

2. For Full Date Pickers

If you’re using a standard date picker (that includes day, month, and year) and want to completely clear all selected values (including month and year), your original approach works perfectly—but combining it with setDate(null) makes it more explicit and reliable across different picker versions:

$('#datepicker').val('').datepicker('setDate', null).datepicker('update');

If you’re looking for a more edge-case scenario—like resetting just the month/year while keeping the selected day—you’ll need to construct a new date object with the current month/year and the existing day value:

// Get the currently selected date
const selectedDate = $('#datepicker').datepicker('getDate');
if (selectedDate) {
  // Create a new date with the same day, but current month/year
  const currentDate = new Date();
  const resetDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), selectedDate.getDate());
  
  // Update the picker
  $('#datepicker').datepicker('setDate', resetDate).datepicker('update');
}

Bonus: Resetting the Picker View Without Clearing Input

If you just want to reset the picker’s dropdown view to the current month/year (but leave the input value untouched), use the setViewDate method:

$('#datepicker').datepicker('setViewDate', new Date());

内容的提问来源于stack exchange,提问作者ilce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:27:51