【问题标题】:asp.net mvc - Set locale / format of a DateTime parameterasp.net mvc - 设置日期时间参数的区域设置/格式
【发布时间】:2016-01-04 13:06:13
【问题描述】:

我正在使用 bootrap 日期时间选择器来允许用户输入日期,如下所示:

<div class="form-group">
    <label for="end">Start date:</label><br />
    <div class='input-group date' id='dt1'>
        @Html.TextBox("StartDateFilter", null, new { @class = "form-control" })
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>

<script type="text/javascript">
    $('#dt1').datetimepicker({
        format: 'L',
        locale: 'en-GB'
    });
</script>

然后,该日期将作为以下方法签名中的参数:

public ActionResult Index(string sortOrder, string sortBy, string currentFilter, string searchString, string filterType, int? itemDisplay, int? page, DateTime? startDateFilter, DateTime? endDateFilter)

但是,文本框中的日期显示为 DD/MM/YYYY,但传递为 MM/DD/YYYY,这会导致一些格式错误和解析错误。如何将参数中的 DateTime 对象的格式或本地更改为 DD/MM/YYYY。

我已经在 system.web 下的 web.config 文件中添加了以下内容:

<globalization culture="en-GB" uiCulture="en-GB" />

提前致谢。

【问题讨论】:

    标签: c# asp.net-mvc validation datetime bootstrap-datetimepicker


    【解决方案1】:

    你可以用这个

    更新

    global.asax

        protected void Application_Start()
        {
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings =
              new JsonSerializerSettings
          {
             DateFormatHandling = DateFormatHandling.IsoDateFormat,
             DateTimeZoneHandling = DateTimeZoneHandling.Unspecified,
             Culture = CultureInfo.GetCultureInfo("en-GB")
          };
    
             Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
        }
    

    【讨论】:

    • 我刚刚尝试将其添加到 global.asax 文件中,我得到:'GlobalConfiguration' 在当前上下文中不存在。任何想法如何解决这个问题?
    • 谢谢,我还以为是 System.Web.Http。只是尝试为其安装软件包,但由于某种原因无法安装,认为这是服务器错误,所以我会在几分钟后重试并测试此答案。我会告诉你我的进展情况。
    • 经过 17 次尝试,我成功安装了软件包哈哈,不知道我今天的网络怎么了!可悲的是,这并没有解决我的问题。日期仍以 MM/DD/YYY 传递,因此格式不正确,当使用超过 12 天时,这将传递为 null。
    • 我遇到了和你一样的问题,这对我有帮助,我不知道你是怎么回事
    • 经过 10 个小时,我终于找到了解决方案。我将日期作为字符串传递。然后检查当用户没有输入过滤器时它是否为空或空。将其转换为日期并强制格式为英国,然后使用这个新的局部变量 datetime 与模型进行比较。可能不是最好的方法,但它确实有效!
    【解决方案2】:

    使用 DateTime.ParseExact 方法在您的方法中格式化输入日期,如下所示:

    DateTime sDate = DateTime.ParseExact(startDateFilter.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
    
    DateTime eDate = DateTime.ParseExact(endDateFilter.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
    

    这是你想要的吗?

    【讨论】:

    • 感谢您的意见,但我不明白这有什么帮助?这只会将 datetimepicker 的显示更改为法国标准。
    • 再次感谢,但这仍然不是我所需要的。这将允许您在通过后更改 DateTime 格式,但我需要在此之前更改它。
    猜你喜欢
    • 2011-03-15
    • 1970-01-01
    • 2011-01-22
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    相关资源
    最近更新 更多