显示英国和美国的日期时间
本文关键字:日期 时间 美国 英国 显示 | 更新日期: 2023-09-27 18:34:50
更新
我想使用通用方式以 24 小时格式显示英国或美国的日期时间值,具体取决于其当前区域性。
代码如下(不是实际代码,仅用于问题(:
var dt = new DateTime(2011, 4, 15, 17, 50, 40);
Console.WriteLine(dt.ToString("d", new CultureInfo("en-us")) + " "
+ dt.ToString("H:mm:ss", new CultureInfo("en-us")));
Console.WriteLine(dt.ToString("G", new CultureInfo("en-gb")));
结果如下:
2011/4/15 17:50:40
2011-04-15 17:50:40
它显示正常。
有没有更好的方法来不使用"H:mm:ss"来显示时间。请注意,美国G显示PM,这不是我想要的。
美国的月份是 4,而不是 04,有没有办法在 04 中显示它。.
更新
以下是我想要的,理想情况下使用通用方式:
美国: 04/15/2011 17:50:40
英国: 15/04/2011 17:50:40
试试这个。
DateTime dt = new DateTime(2011, 4, 15, 17, 50, 40);
Console.WriteLine(dt.ToString("MM/dd/yyy H:mm:ss"));// US format
Console.WriteLine(dt.ToString("dd/MM/yyy H:mm:ss"));// UK format
来自 MSDN 的自定义日期和时间格式字符串
您可以像这样编写自己的自定义显示,
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(@"MM/dd/yy HH':mm':ss"));
Console.ReadLine();
// Displays 05/20/12 17:08:37
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
您可以为美国做这样的事情:
CultureInfo ci = new CultureInfo("en-us", true);
ci.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
ci.DateTimeFormat.LongTimePattern = "HH:mm:ss";
ci.DateTimeFormat.AMDesignator = "";
ci.DateTimeFormat.PMDesignator = "";
现在,您可以像这样设置当前线程区域性:
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
并像这样显示日期:
Console.WriteLine(dt.ToString("G"));
或者,可以将区域性作为参数传递给 ToString 方法,如下所示:
Console.WriteLine(dt.ToString("G", ci));
如果你更喜欢第二种方法,你可以将上面的代码包装在一个静态方法中,这样你就可以像这样调用它:
Console.WriteLine(dt.ToString("G", Cultures.EnUs));