【问题标题】:Google Chrome is showing the date format yyyy-MM-dd instead of dd/MM/yyyy谷歌浏览器显示日期格式 yyyy-MM-dd 而不是 dd/MM/yyyy
【发布时间】:2018-02-01 17:59:31
【问题描述】:

指定值"18/08/2017"不符合要求的格式,yyyy-MM-dd

Google Chrome 不会从控制器方法加载 dd/MM/yyyy 格式的日期。我想将日期加载到日期类型字段中。谷歌浏览器给了我一个警告。我该如何解决这个问题

指定的值"18/08/2017"不符合要求的格式,yyyy-MM-dd

这是我在视图中的代码

@Html.EditorFor(model => model.DateReceived, "{0:dd/MM/yyyy}", 
    new {htmlAttributes = new { @class = "form-control", @type="date" } })

【问题讨论】:

  • 我会将输入类型保留为文本并使用一些 jquery 插件来选择日期,因为日期输入类型仅在 chrome 中显示 datepicker 而在其他浏览器中不起作用。

标签: c# asp.net asp.net-mvc date-format html5-input-date


【解决方案1】:

Chrome 想要“yyyy-MM-dd”-> 2017/08/18
你给了 chrome "dd-MM-yyyy" -> 2017 年 8 月 18 日
您需要为 Chrome 提供所需的格式。

改为:

@Html.EditorFor(model => model.DateReceived, "{0:yyyy/MM/dd}", new {htmlAttributes = new { @class = "form-control", @type="date" } })

【讨论】:

  • 还是不行。我将其更改为 @Html.EditorFor(model => model.DateReceived, "{0:yyyy/MM/dd}", new { htmlAttributes = new { @class= "form-control" } }) 和 DisplayFormat 也相同模态
【解决方案2】:

请在您的页面中编写以下 javascript

<script type="text/jscript">   
    $(function () {
        $.validator.methods.date = function (value, element) {
            if ($.browser.webkit) {

                //ES - Chrome does not use the locale when new Date objects instantiated:
                var d = new Date();

                return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
            }
            else {

                return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
            }
        };
    });

并考虑写这个

@Html.EditorFor(model => model.DateReceived, "{0:dd/MM/yyyy}", 
 new { @class = "form-control" })

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2019-10-29
    相关资源
    最近更新 更多