asp.net-mvc 在 ASP.NET MVC 应用程序中更改日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17106105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:56:55  来源:igfitidea点击:

Change date format in ASP.NET MVC application

asp.net-mvcasp.net-mvc-3asp.net-mvc-4razormvc-editor-templates

提问by Andrei

I need to change date format to be dd.MM.yyyy. I am getting client side validation error because ASP.NET MVC date format is different from what I expect on the server.

我需要将日期格式更改为dd.MM.yyyy. 我收到客户端验证错误,因为 ASP.NET MVC 日期格式与我在服务器上期望的不同。

In order to change ASP.NET MVC date format I tried:

为了更改 ASP.NET MVC 日期格式,我尝试了:

Web.config:

网页配置:

<globalization uiCulture="ru-RU" culture="ru-RU" />

Model:

模型:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime? ServiceCreatedFrom { get; set; }

Editor template:

编辑器模板:

@model DateTime?
@Html.TextBox(string.Empty, (Model.HasValue 
    ? Model.Value.ToString("dd.MM.yyyy")
    : string.Empty), new { @class = "date" })

View:

看法:

@Html.EditorFor(m => m.ServiceCreatedFrom, new { @class = "date" })

Even Global.asax:

甚至 Global.asax:

public MvcApplication()
{
    BeginRequest += (sender, args) =>
        {
            var culture = new System.Globalization.CultureInfo("ru");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        };
}

Nothing worked for me.

没有什么对我有用。

采纳答案by Darin Dimitrov

The following should work:

以下应该工作:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime? ServiceCreatedFrom { get; set; }

and in your editor template:

并在您的编辑器模板中:

@model DateTime?
@Html.TextBox(
    string.Empty, 
    ViewData.TemplateInfo.FormattedModelValue, 
    new { @class = "date" }
)

and then:

进而:

@Html.EditorFor(x => x.ServiceCreatedFrom)

The second argument you were passing to the EditorFor call doesn't do what you think it does.

您传递给 EditorFor 调用的第二个参数与您认为的不同。

For this custom editor template, since you specified the format explicitly on your view model property the <globalization>element in your web.config and the current thread culture will have 0 effect. The current thread culture is used with the standard templates and when you didn't override the format with the [DisplayFormat]attribute.

对于此自定义编辑器模板,由于您在视图模型属性上明确指定了格式<globalization>,因此 web.config 中的元素和当前线程文化将具有 0 效果。当前线程区域性与标准模板一起使用,并且当您没有使用[DisplayFormat]属性覆盖格式时。

回答by shaijut

finally thisone worked for me to get this dd/mm/yyyy format i used date = string.Format("{0}/{1}/{2}", Model.Value.Day, Model.Value.Month, Model.Value.Year);

最后这个对我有用,得到了我使用的这种 dd/mm/yyyy 格式date = string.Format("{0}/{1}/{2}", Model.Value.Day, Model.Value.Month, Model.Value.Year);

first create EditorTemplates folder in Sharedfolder, then create a Datetime editor template in Sharedfolder/EditorTemplates/Datetime.cshtmlthen follow the above link.

首先在 Sharedfolder 中创建 EditorTemplates 文件夹,然后在其中创建一个 Datetime 编辑器模板,Sharedfolder/EditorTemplates/Datetime.cshtml然后按照上面的链接操作。

in view

鉴于

@Html.EditorFor(x => x.ServiceCreatedFrom)

@Html.EditorFor(x => x.ServiceCreatedFrom)

hope helps someone.

希望能帮助某人。

回答by RAVI VAGHELA

You can change the current culture in your Global.asax file, for application level For Example,

您可以更改 Global.asax 文件中的当前文化,例如应用程序级别,

using System.Globalization;
using System.Threading;

protected void Application_BeginRequest(Object sender, EventArgs e)
{    
  CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
  newCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
  newCulture.DateTimeFormat.DateSeparator = "-";
  Thread.CurrentThread.CurrentCulture = newCulture;
}

回答by sammy34

As a potential aid for identifying the issue, are you able to: 1. Set a breakpoint at the point where you're trying to format the date 2. Use something like the Immediate Window in Visual Studio to evaluate the value of

作为识别问题的潜在帮助,您是否能够: 1. 在您尝试格式化日期的位置设置断点 2. 使用类似 Visual Studio 中的立即窗口之类的东西来评估

Thread.CurrentThread.CurrentCulture.Name

If you do this, does it come back with the "ru-RU" culture?

如果你这样做,它是否会随着“ru-RU”文化回归?

I'm sure I'm not the only one that would be happy to help you work through debugging this. That said, perhaps somebody quicker than me can see the problem straight away :).

我敢肯定,我不是唯一一个乐于帮助您解决此问题的人。也就是说,也许比我更快的人可以立即看到问题:)。

Edit: It looks like you're using Razor, so you should be able to set a breakpoint directly in the view file on the line where you're trying to format the date.

编辑:看起来您正在使用 Razor,因此您应该能够直接在视图文件中尝试设置日期格式的行上设置断点。

Edit #2:

编辑#2:

There may be a cleaner way to do this, but if the form data is being posted in dd.MM.yyyy then you might need a custom model binder, something like:

可能有一种更简洁的方法来做到这一点,但如果表单数据是在 dd.MM.yyyy 中发布的,那么您可能需要一个自定义模型绑定器,例如:

public class CustomModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
              // custom bind the posted date    
        }
}

...which would then get assigned as a model binder in e.g. ApplicationStart in Global.asax.cs.

...然后将被分配为例如 Global.asax.cs 中的 ApplicationStart 中的模型绑定器。

Let me know if you think this might help and I can elaborate.

如果您认为这可能会有所帮助,请告诉我,我可以详细说明。