【问题标题】:Set DateTime Format for UpdateModel为 UpdateModel 设置日期时间格式
【发布时间】:2012-04-11 00:41:37
【问题描述】:

考虑以下模型:

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 TextBox 上的数据为 2012 年 2 月 4 日时,UpdateModel() 将 StartDate 设置为 2012 年 2 月 4 日而不是 2012 年 4 月 2 日,是否有充分的理由?

【问题讨论】:

    标签: c# jquery asp.net-mvc


    【解决方案1】:

    这取决于解析输入的计算机的文化设置。因此,如果网络服务器设置为基于 en-US 文化解析DateTime,即使网页设置为将其呈现为dd/MM/yyyy,它也会将其解析为MM/dd/yyyy。如果您想强制解析始终为一种格式,则必须在自定义活页夹中调用 DateTime.Parse 时传入文化信息。

    编辑:实际上我认为这可以在 web.config 中设置为应用程序使用默认文化。虽然我不确定如何做到这一点,但没有使用不同的文化环境。

    MSDN 有一篇很好的文章,介绍了可与 MVC 一起使用的 ASP.NET 应用程序全球化。 StackOverflow 上的 this article 也将解释如何在 web.config 中使用 MVC 进行操作。如果您按照那里的答案,它应该会自动以您正在寻找的格式解析 DateTime。

    【讨论】:

    • 您能否发布一个示例,说明我应该如何告诉 UpdateModel 我想使用的文化?
    【解决方案2】:

    2/4/2012 是美国英语文化的标准日期时间格式。它表示 2012 年 2 月 4 日。英国英语文化的相同日期时间格式表示 2012 年 4 月 2 日。

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

    【讨论】:

    • 但我将模型上的日期格式设置为 dd/MM/yyyy。为什么 UpdateModel 仍然使用美国格式?
    • Adam Gritt 在这个问题上击败了我。
    猜你喜欢
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多