设置更新模型的日期时间格式

本文关键字:时间 格式 日期 更新 模型 设置 | 更新日期: 2023-09-27 18:30:43

考虑以下模型:

public class ExportRequestsFilter {
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? StartDate { get; set; }
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? EndDate { get; set; }
    ...

根据各自的观点:

<script type="text/javascript">
    $(document).ready(function () {
        $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' }); // this is the datepicker equivalent to dd/MM/yyyy
    });
</script>
...
<% using (Html.BeginForm(FormMethod.Post)) {%>
    ...
    <%: Html.TextBox("StartDate", Model.StartDate, new { @class = "datepicker" })%><br />
    <%: Html.TextBox("EndDate", Model.EndDate, new { @class = "datepicker" })%>
    <input type="submit" class="buttonLink" name="submitButton" value="<%: Html.Resource("Preview") %>" />
当 StartDate 文本框上的数据为 2/4/2012,UpdateModel()将 StartDate 设置为 2012 年 2 月 4 日

而不是 2012 年 4 月 2 日时,是否有任何充分的理由?

设置更新模型的日期时间格式

这取决于执行输入分析的计算机的区域性设置。 因此,如果 Web 服务器设置为基于 en-US 区域性解析DateTime,即使网页设置为将其呈现为 dd/MM/yyyy,它也会将其解析为MM/dd/yyyy。 如果要强制分析始终采用一种格式,则必须在自定义绑定程序内调用 DateTime.Parse 时传入区域性信息。

编辑:实际上我认为可以在web.config中设置这以使用应用程序的默认区域性。 没有使用过不同的文化设置,尽管我不确定该怎么做。

MSDN 有一篇关于全球化 ASP.NET 应用程序的好文章,这些应用程序将与 MVC 配合使用。 此外,这篇关于StackOverflow的文章将解释如何在web.config中使用MVC来做到这一点。 如果您按照那里的答案进行操作,它应该会自动以您要查找的格式解析日期时间。

> 2/4/2012 是美国英语区域性的标准日期时间格式。这意味着2012年2月4日。英国英语区域性的相同日期时间格式表示 2012 年 4 月 2 日。

听起来您当前的 UI 区域性设置为en-US,而不是en-UK。您可以通过检查System.Globalization.CultureInfo.CurrentUICulture来检查它。