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

ASP.NET Core 8 MVC中日期格式提交异常问题的解决方法

ASP.NET Core 8 MVC日期格式转换异常解决方案

问题描述

在Visual Studio开发ASP.NET Core 8 MVC项目时,遇到日期格式转换异常:

  • 输入15.10.2023(日.月.年),后台接收后显示为0001.01.01
  • 输入5.6.2023,后台显示为6.5.2023(月和日被颠倒)

相关代码

视图HTML代码

<form method="post"
      asp-action="GetVillasByDate">
    <div class="row p-0 mx-0 py-4">

        <div class="col-12 col-md-5  offset-md-1 pl-2  pr-2 pr-md-0">
            <div class="form-group">
                <label>Check In Date</label>
                <input asp-for="CheckInDate" type="date" class="form-control" />
            </div>
        </div>

        <div class="col-8 col-md-3 pl-2 pr-2">
            <div class="form-group">
                <label>No. of nights</label>
                <select class="form-select" asp-for="Nights">
                    @for(var i = 1; i<11; i++)
                    {
                        <option value="@i">@i</option>
                    }
                </select>
            </div>
        </div>

        <div class="col-4 col-md-2 pt-4 pr-2">
            <div class="form-group">
                <button type="button" onclick="fnLoadVillaList()" class="btn btn-success btn-block">
                    <i class="bi bi-search"></i>  &nbsp; Check Availability
                </button>

            </div>
        </div>

    </div>
    <partial name="_VillaList" model="Model" />
</form>

脚本代码

@section scripts {
    <script>
        function fnLoadVillaList() {
            $('.spinner').show();
            var objData = {
                
                checkInDate: $("#CheckInDate").val(),
                nights: $("#Nights").val()
            };

            $.ajax({
                type: "POST",
                data: objData,
                url: "@Url.Action("GetVillasByDate", "Home")",
                success: function (data) {
                    $("#VillasList").empty();
                    $("#VillasList").html(data);
                    $('.spinner').hide();
                },
                failure: function (response) {
                    $('.spinner').hide();
                    alert(response.responseText);
                },
                error: function (response) {
                    $('.spinner').hide();
                    alert(response.responseText);
                }
            });
        }
    </script>
}

解决步骤

1. 前端统一日期格式为ISO 8601标准

HTML原生type="date"输入框默认返回YYYY-MM-DD格式,但手动输入DD.MM.YYYY这类格式时,浏览器无法正确解析,导致后台绑定出错。修改JS函数,强制转换为标准格式:

function fnLoadVillaList() {
    $('.spinner').show();
    // 处理DD.MM.YYYY格式转为YYYY-MM-DD
    let rawDate = $("#CheckInDate").val();
    let formattedDate = rawDate;
    if (rawDate.includes('.')) {
        const parts = rawDate.split('.');
        // 补零确保格式统一(比如5.6.2023 → 2023-06-05)
        formattedDate = `${parts[2]}-${parts[1].padStart(2, '0')}-${parts[0].padStart(2, '0')}`;
    }

    var objData = {
        checkInDate: formattedDate,
        nights: $("#Nights").val()
    };

    $.ajax({
        type: "POST",
        data: objData,
        url: "@Url.Action("GetVillasByDate", "Home")",
        success: function (data) {
            $("#VillasList").empty();
            $("#VillasList").html(data);
            $('.spinner').hide();
        },
        failure: function (response) {
            $('.spinner').hide();
            alert(response.responseText);
        },
        error: function (response) {
            $('.spinner').hide();
            alert(response.responseText);
        }
    });
}

2. 后台配置多格式日期绑定

ASP.NET Core默认日期绑定规则不支持DD.MM.YYYY,可以通过自定义模型绑定器兼容多种格式:

自定义日期绑定器

public class DateTimeModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == ValueProviderResult.None)
            return Task.CompletedTask;

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

        var dateString = valueProviderResult.FirstValue;
        if (string.IsNullOrEmpty(dateString))
            return Task.CompletedTask;

        // 支持的日期格式列表
        var formats = new[] { "yyyy-MM-dd", "dd.MM.yyyy", "d.M.yyyy" };
        if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date))
        {
            bindingContext.Result = ModelBindingResult.Success(date);
        }
        else
        {
            bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "日期格式无效,请使用DD.MM.YYYY或YYYY-MM-DD格式");
        }

        return Task.CompletedTask;
    }
}

在模型属性上标记绑定器

public class VillaSearchViewModel
{
    [ModelBinder(BinderType = typeof(DateTimeModelBinder))]
    public DateTime CheckInDate { get; set; }
    public int Nights { get; set; }
}

3. 前端限制输入格式(可选)

添加输入校验或使用日期选择器,避免用户输入非标准格式:

<input asp-for="CheckInDate" type="date" class="form-control" 
       pattern="\d{2}\.\d{2}\.\d{4}" 
       title="请输入DD.MM.YYYY格式的日期" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:07:04