Reputation: 7170
Consider the following Model:
public class ExportRequestsFilter {
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? StartDate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? EndDate { get; set; }
...
With the respective View:
<script type="text/javascript">
$(document).ready(function () {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' }); // this is the datepicker equivalent to dd/MM/yyyy
});
</script>
...
<% using (Html.BeginForm(FormMethod.Post)) {%>
...
<%: Html.TextBox("StartDate", Model.StartDate, new { @class = "datepicker" })%><br />
<%: Html.TextBox("EndDate", Model.EndDate, new { @class = "datepicker" })%>
<input type="submit" class="buttonLink" name="submitButton" value="<%: Html.Resource("Preview") %>" />
Is there any good reason for when the data on StartDate TextBox is 2/4/2012, UpdateModel()
sets the StartDate to 4 February 2012 instead of 2 April 2012?
Upvotes: 0
Views: 1153
Reputation: 2674
It depends on the culture settings for the computer doing the parsing of the input. So if the webserver is set to parse the DateTime
based on en-US culture it will parse it as MM/dd/yyyy
even though the webpage is setup to render it as dd/MM/yyyy
. If you want to force the parsing to always be of one format then you have to pass in the Culture information when you call DateTime.Parse inside a custom binder.
EDIT: Actually I think this can be set in the web.config to use a default culture for the application. Having not worked with different culture settings though I don't know for sure how to do this.
MSDN has a good article on globalizing ASP.NET applications that would work with MVC. Also this article on StackOverflow would explain how to do it with MVC in the web.config. If you follow the answer there it should automatically parse the DateTime in the format you are looking for.
Upvotes: 1
Reputation: 47375
2/4/2012 is the standard datetime format for the US english culture. It means Feb 4th 2012. The same datetime format for the UK english culture means April 2nd 2012.
It sounds like your current UI culture is set to en-US, not en-UK. You can check it by inspecting System.Globalization.CultureInfo.CurrentUICulture
.
Upvotes: 1