问题
I am using the bootrap datetime picker to allow the user to enter a date, show below:
<div class="form-group">
<label for="end">Start date:</label><br />
<div class='input-group date' id='dt1'>
@Html.TextBox("StartDateFilter", null, new { @class = "form-control" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<script type="text/javascript">
$('#dt1').datetimepicker({
format: 'L',
locale: 'en-GB'
});
</script>
This date then gets picked up as a parameter in the following method signature:
public ActionResult Index(string sortOrder, string sortBy, string currentFilter, string searchString, string filterType, int? itemDisplay, int? page, DateTime? startDateFilter, DateTime? endDateFilter)
However, the date in the textbox is being displayed as DD/MM/YYYY but passed as MM/DD/YYYY which causes several formatting errors and parsing errors. How can I change the format or local of the DateTime objects that are in the parameters to DD/MM/YYYY.
I have already added the following to my web.config file under system.web:
<globalization culture="en-GB" uiCulture="en-GB" />
Thanks in advance.
回答1:
you can use this
UPDATED
global.asax
protected void Application_Start()
{
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Unspecified,
Culture = CultureInfo.GetCultureInfo("en-GB")
};
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
}
回答2:
Use DateTime.ParseExact method to format the input date in your method as follow:
DateTime sDate = DateTime.ParseExact(startDateFilter.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime eDate = DateTime.ParseExact(endDateFilter.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
is this what you want?
来源:https://stackoverflow.com/questions/34591888/asp-net-mvc-set-locale-format-of-a-datetime-parameter