在 C# 中格式化日期 [英] format date in c#
问题描述
如何将日期格式化为 dd/mm/yyyy
或 mm/dd/yy
?
How can I format a date as dd/mm/yyyy
or mm/dd/yy
?
就像在 VB format("dd/mm/yy",now)
如何在 C# 中执行此操作?
How can I do this in C#?
推荐答案
几乎一样,只需使用 DateTime.ToString()
方法,例如:
It's almost the same, simply use the DateTime.ToString()
method, e.g:
DateTime.Now.ToString("dd/MM/yy");
或者:
DateTime dt = GetDate(); // GetDate() returns some date
dt.ToString("dd/MM/yy");
此外,您可能需要考虑使用一种预定义的日期/时间格式,例如:
In addition, you might want to consider using one of the predefined date/time formats, e.g:
DateTime.Now.ToString("g");
// returns "02/01/2009 9:07 PM" for en-US
// or "01.02.2009 21:07" for de-CH
这些确保格式正确,与当前的区域设置无关.
These ensure that the format will be correct, independent of the current locale settings.
查看以下 MSDN 页面以获取更多信息
Check the following MSDN pages for more information
一些额外的相关信息:
如果您想以特定的语言环境/文化显示日期,则有一个采用 IFormatProvider
的 ToString()
方法的重载:
If you want to display a date in a specific locale / culture, then there is an overload of the ToString()
method that takes an IFormatProvider
:
DateTime dt = GetDate();
dt.ToString("g", new CultureInfo("en-US")); // returns "5/26/2009 10:39 PM"
dt.ToString("g", new CultureInfo("de-CH")); // returns "26.05.2009 22:39"
或者,您可以在格式化日期之前设置当前线程的CultureInfo
:
Or alternatively, you can set the CultureInfo
of the current thread prior to formatting a date:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
dt.ToString("g"); // returns "5/26/2009 10:39 PM"
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-CH");
dt.ToString("g"); // returns "26.05.2009 22:39"
这篇关于在 C# 中格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!