Skip to main content
 首页 » 编程设计

c#之更改 Razor 的默认日期时间格式

2024年02月13日13rubylouvre

有没有一种方法可以将所有 DateTime 对象的默认格式更改为例如Razor 中的“dd.MM.yyyy”?

我想涵盖程序员忘记调用扩展方法或传递格式字符串的情况,即 <p>@Model.MyDateTimeObject</p> .

请您参考如下方法:

Razor 中没有默认格式。当你这样做时:<p>@Model.MyDateTimeObject</p> Razor 将简单地使用默认的 DateTime.ToString重载以打印日期。

这取决于实际的文化信息,例如,如果您希望您的示例作为默认的 ToString 行为,那么您应该为实际请求更改当前的文化。例如。在 global.asax 中:

protected void Application_BeginRequest() 
{ 
    CultureInfo culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); 
    culture.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy"; 
    culture.DateTimeFormat.LongTimePattern = ""; 
    Thread.CurrentThread.CurrentCulture = culture; 
}