有没有办法设置或覆盖整个应用程序的默认日期时间格式。我正在用 C# .Net MVC 1.0 编写一个应用程序,并使用大量泛型和反射。如果我可以将默认的 DateTime.ToString() 格式重写为“dd-MMM-yyyy”,则会简单得多。当站点在不同的计算机上运行时,我不希望更改此格式。
编辑 -
只是为了澄清,我的意思是专门调用 ToString,而不是其他扩展函数,这是因为反射/生成的代码。只需更改 ToString 输出会更容易。
日期时间的“默认格式”是:
ShortDatePattern + ' ' + LongTimePattern
至少在当前单声道实现 https://github.com/mono/mono/blob/master/mcs/class/corlib/System/DateTimeUtils.cs#L117。
如果您想要显示类似 2001-02-03T04:05:06Z 的内容(即按照中指定的日期和时间组合),这尤其令人痛苦ISO 8606 http://en.wikipedia.org/wiki/ISO_8601,但对你来说这不是一个大问题:
using System;
using System.Globalization;
using System.Threading;
namespace test {
public static class Program {
public static void Main() {
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
culture.DateTimeFormat.LongTimePattern = "";
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(DateTime.Now);
}
}
}
这将设置 ToString 在日期时间上的默认行为,以返回您期望的格式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)