简体   繁体   English

asp.net mvc-设置日期时间参数的语言环境/格式

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

I am using the bootrap datetime picker to allow the user to enter a date, show below: 我正在使用bootrap日期时间选择器来允许用户输入日期,如下所示:

<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. 但是,文本框中的日期显示为DD / MM / YYYY,但传递为MM / DD / YYYY,这会导致一些格式错误和解析错误。 How can I change the format or local of the DateTime objects that are in the parameters to DD/MM/YYYY. 如何将参数中的DateTime对象的格式或本地更改为DD / MM / YYYY。

I have already added the following to my web.config file under system.web: 我已经在system.web下的web.config文件中添加了以下内容:

<globalization culture="en-GB" uiCulture="en-GB" />

Thanks in advance. 提前致谢。

you can use this 你可以用这个

UPDATED 更新

global.asax 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");
    }

Use DateTime.ParseExact method to format the input date in your method as follow: 使用DateTime.ParseExact方法来格式化方法中的输入日期,如下所示:

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? 这是你想要的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM