Casper Nybroe
Casper Nybroe

Reputation: 1199

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

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>

Upvotes: 2

Views: 5168

Answers (2)

Michal Pokluda
Michal Pokluda

Reputation: 390

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'
});

Upvotes: 0

ethorn10
ethorn10

Reputation: 1899

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.

Upvotes: 1

Related Questions