asp.net mvc - Set locale / format of a DateTime parameter

风流意气都作罢 提交于 2019-12-12 03:25:54

问题


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

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