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

如何在Bootstrap DateTimePicker中从模型设置日期而非默认当前日期?

解决Bootstrap DateTimePicker始终显示当前日期而非模型值的问题

我来帮你排查这个问题,看起来是DateTimePicker的默认行为和你的模型绑定逻辑冲突了,咱们一步步解决:

问题根源

  1. 你手动在EditorFor里添加了@Value = Model.ApplyDate,但@Html.EditorFor本身已经会自动根据模型值生成输入框的value属性,手动赋值可能导致格式不匹配或者覆盖问题。
  2. Bootstrap DateTimePicker默认开启了useCurrent: true选项——如果输入框的值无法被正确解析(或者为空),控件会自动把当前日期设为显示值。

解决方案

步骤1:修正EditorFor代码,移除手动Value赋值

删掉@Value = Model.ApplyDate,让EditorFor自动处理模型绑定:

@Html.EditorFor(model => model.ApplyDate, new { htmlAttributes = new { @class = "form-control datepicker", placeholder = "dd/mm/yyyy", tabindex = "5", maxlength = "10", required = "" } })

步骤2:修改DateTimePicker配置,禁用自动使用当前日期

在你的JS配置里添加useCurrent: false,同时可以去掉defaultDate: null(因为useCurrent: false已经会让控件优先使用输入框的现有值):

$('.datepicker').datetimepicker({
    format: 'DD/MM/YYYY',
    locale: 'es',
    icons: {
        time: "fas fa-clock",
        date: "fas fa-calendar-alt",
        up: "fas fa-arrow-up",
        down: "fas fa-arrow-down",
        previous: "fas fa-chevron-left",
        next: "fas fa-chevron-right"
    },
    daysOfWeekDisabled: [0, 6],
    useCurrent: false // 关键:阻止控件自动设置为当前日期
});

额外检查点

  • 确认Model.ApplyDate不是null或者DateTime.MinValue,如果是这两种情况,输入框会是空的,控件会显示空而不是当前日期(符合预期)。
  • 确保Model.ApplyDate的格式和DateTimePicker的format: 'DD/MM/YYYY'一致,你可以在模型属性上添加特性统一格式:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime ApplyDate { get; set; }

这样调整后,DateTimePicker就会正确显示模型中的日期值,而不是默认的当前日期了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:08:24