.NET datepicker format gives “MM-dd-yyyy” instead of “MM/dd/yyyy”

强颜欢笑 提交于 2019-12-11 03:17:36

问题


I have created a datepicker in my MVC that works fine but when i pick a date I get the format "MM/dd/yyyy". When I save that, it changes back to "MM-dd-yyyy". If i try to save with this format the datepicker says that it is not a valid date because it has changed the seperater from "/" to "-". So I wish to maintain a format like this "MM/dd/yyyy".

Here is my code for the field where the datepicker is implemented:

   @Html.ValidationSummary(true)
   @Html.HiddenFor(model => model.Id)
   <div class="form-group">
        @Html.LabelFor(model => model.TimeFrom, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @*@Html.EditorFor(model => model.TimeFrom)*@
            @Html.TextBoxFor(model => model.TimeFrom, "{0:MM/dd/yyyy}", new { @class = "datepicker form-control"})
            @Html.ValidationMessageFor(model => model.TimeFrom)
        </div>
   </div>

And this is for my datepicker:

<script type="text/javascript">
$(document).ready(function () {
    $('.datepicker').each(function () {
        $(this).datepicker({
            changeMonth: true,
            changeYear: true
        });
    });
});
</script>

回答1:


Add the format to your datepicker options:

<script type="text/javascript">
$(document).ready(function () {
    $('.datepicker').each(function () {
        $(this).datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: "mm/dd/yy"
        });
    });
});
</script>

The datepicker format is slightly different from the ASP.NET format. mm is the equivalent of MM, and yy is the equivalent of yyyy.




回答2:


The only way I've been able to make it work to use my desired format of date "dd.mm.yyyy" was like this:

For the razor syntax I had to use TextBoxFor (if you use EditorFor, Chrome won't work correctly):

@{ Html.EnableClientValidation(false); }
@Html.TextBoxFor(model => model.Date, new { 
    @Value = Model.Date.ToString("dd.MM.yyyy"),  
    @class = "datepicker",
    placeholder = "Enter date here..." }
)
@{ Html.EnableClientValidation(true); }

In the model declaration need to add some attributes:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }

And a little javascript code:

$('.datepicker').datepicker({
    dateFormat: 'dd.mm.yy'
});


来源:https://stackoverflow.com/questions/27453428/net-datepicker-format-gives-mm-dd-yyyy-instead-of-mm-dd-yyyy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!