经过一番挖掘,我最终将Thread 的CurrentCulture 值设置为在控制器的操作方法中包含CultureInfo("en-US"):
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
这里有一些other options,如果你想在每个视图上都有这个设置。
关于CurrentCulture属性值:
此属性返回的CultureInfo 对象,一起
及其关联对象,确定日期的默认格式,
时间、数字、货币值、文本排序顺序、大小写
约定和字符串比较。
来源:MSDN CurrentCulture
注意:如果控制器已经使用CultureInfo("en-US") 或类似日期格式为"MM/dd/yyyy" 的控制器运行,则之前的CurrentCulture 属性设置可能是可选的。
设置CurrentCulture属性后,在视图中添加代码块将日期转换为"M/d/yyyy"格式:
@{ //code block
var shortDateLocalFormat = "";
if (Model.AuditDate.HasValue) {
shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("M/d/yyyy");
//alternative way below
//shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("d");
}
}
@shortDateLocalFormat
@shortDateLocalFormat 变量上方的格式为 ToString("M/d/yyyy") 作品。如果使用ToString("MM/dd/yyyy"),就像我第一次做的那样,那么你最终会得到leading zero issue。也像Tommy 推荐的ToString("d") 一样有效。实际上"d" 代表“Short date pattern”,也可以用于不同的文化/语言格式。
我猜上面的代码块也可以用一些cool helper method或类似的代替。
例如
@helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("M/d/yyyy");
}
@shortDateLocalFormat
}
可以与这个助手调用一起使用
@DateFormatter(Model.AuditDate)
更新,我发现当使用DateTime.ToString(String, IFormatProvider) 方法时,还有另一种方法可以做同样的事情。使用此方法时,无需使用Thread 的CurrentCulture 属性。 CultureInfo("en-US") 作为第二个参数传递 --> IFormatProvider 到 DateTime.ToString(String, IFormatProvider) 方法。
修改辅助方法:
@helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("d", new System.Globalization.CultureInfo("en-US"));
}
@shortDateLocalFormat
}
.NET Fiddle