airDatepickerInput月份显示异常求助:选中一月却显示2020-00
修复airDatepickerInput选中一月显示"2020-00"的问题
这个问题是因为组件解析仅年月格式的日期时,对一月(JS中月份索引为0)的格式化处理出错,导致月份显示为"00"。可以通过以下两种方式修复:
方法一:统一使用完整日期格式参数
将所有日期相关参数(value、minDate、maxDate)改为完整的Date对象或带日的日期字符串,避免仅传年月格式引发解析异常:
ui <- fluidPage( titlePanel("Test"), mainPanel( airDatepickerInput("plot_input_daterange", label = "Please choose:", range = TRUE, # 使用带日的Date对象而非仅年月字符串 value = c(as.Date("2021-10-01"), Sys.Date()), clearButton = TRUE, maxDate = Sys.Date(), minDate = as.Date("2021-10-01"), view = "months", minView = "months", dateFormat = "yyyy-mm", language= "en", addon = "none") ) ) server <- function(input, output) {} shinyApp(ui = ui, server = server)
方法二:添加回调函数修正月份显示
如果仍存在问题,可通过onSelect回调函数手动修正选中日期的显示值,确保月份格式正确:
ui <- fluidPage( titlePanel("Test"), mainPanel( airDatepickerInput("plot_input_daterange", label = "Please choose:", range = TRUE, value = c("2021-10", format(Sys.Date(), "%Y-%m")), clearButton = TRUE, maxDate = format(Sys.Date(), "%Y-%m"), minDate = "2021-10-01", view = "months", minView = "months", dateFormat = "yyyy-mm", language= "en", addon = "none", # 回调函数修正显示格式 onSelect = I("function(selectedDates) { if (selectedDates.length === 2) { const formattedStart = this.formatDate(selectedDates[0], 'yyyy-mm'); const formattedEnd = this.formatDate(selectedDates[1], 'yyyy-mm'); // 强制替换输入框显示内容,修正月份为两位有效数字 this.$el.find('.datepicker-input').val(formattedStart.replace('-00', '-01') + ' - ' + formattedEnd.replace('-00', '-01')); } }") ) ) ) server <- function(input, output) {} shinyApp(ui = ui, server = server)
推荐优先使用方法一,它通过规范参数格式从根源避免解析错误,更简洁可靠。
内容的提问来源于stack exchange,提问作者Philipp Schulz
相关产品推荐
相关产品推荐

