【问题标题】:How can the datetimepicker format be set in a browser specific way?如何以特定于浏览器的方式设置 datetimepicker 格式?
【发布时间】:2016-11-30 16:44:27
【问题描述】:

我们正在开发一个 ASP.NET MVC Web 应用程序,该应用程序在前端使用 Bootstrap 的 datetimepicker 进行选择。我们需要为所有主流浏览器的最新版本提供支持。

Chrome 要求日期格式为“yyyy-MM-dd”以解决如下错误:

指定的值“11/18/2016 00:00:00”不符合 所需格式,“yyyy-MM-dd”。

这会导致一个问题,因为当使用以下代码时,format 选项可以正常工作(即用户可以单击日期并将其设置在输入框中):

    $('.datetimepicker').datetimepicker({
        format: 'YYYY-MM-DD',
        showTodayButton: true,
        showClose: true
    }); 

但是,此代码导致 Firefox 和 IE 不使用设置的 value 属性:

    <div class="form-group">
        @Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control datetimepicker", type = "date", @Value = Model.StartDate } })
            @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
        </div>
    </div>

删除 format: 'YYYY-MM-DD' 会导致 Firefox 和 IE 正常工作,但代价是 Chrome 不再工作。有没有办法以浏览器特定的方式设置format

【问题讨论】:

    标签: asp.net-mvc google-chrome bootstrap-datetimepicker


    【解决方案1】:

    这不是世界上最优雅的解决方案,但由于我们需要了解浏览器的其他功能,因此我们在服务器端根据 Request.UserAgent 设置标志,然后在客户端使用这些标志:

    服务器 C#

    ViewBag.Chrome = userAgent.Contains("Chrome");
    

    客户端 JavaScript

    $('.datetimepicker').datetimepicker({
        showTodayButton: true,
        showClose: true,
        @if (ViewBag.Chrome)
        {
            <text>format: 'YYYY-MM-DD'</text>
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-20
      • 2018-01-15
      • 1970-01-01
      • 2013-04-20
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      相关资源
      最近更新 更多