Search code examples
asp.net-mvcgoogle-chromebootstrap-datetimepicker

How can the datetimepicker format be set in a browser specific way?


We are developing an ASP.NET MVC web application that uses Bootstrap's datetimepicker on the front end for selections. We need to provide support for the latest version of all major browsers.

Chrome requires that dates be formatted as 'yyyy-MM-dd' to resolve errors such as the following:

The specified value "11/18/2016 00:00:00" does not conform to the required format, "yyyy-MM-dd".

This causes a problem since the format option works correctly (i.e. user can click the date and have it set in the input box) when the following code is used:

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

However, this code causes Firefox and IE to not make use of the value attribute that is set:

    <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>

Removing format: 'YYYY-MM-DD' causes Firefox and IE to work correctly at the expense of Chrome no longer working. Is there a way to set the format in a browser specific way?


Solution

  • Not the most elegant solution in the world, but since we need to know the browser for other things, we are setting flags on the server side based upon the Request.UserAgent and then using those flags client side:

    Server C#

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

    Client JavaScript

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