C#DateTime从yyyy-MM-ddTHH:mm:ss转换为dd MMM yyyy [英] C# DateTime Conversion from yyyy-MM-ddTHH:mm:ss to dd MMM yyyy
问题描述
如何将 yyyy-MM-ddTHH:mm:ss转换为 dd MMM yyyy格式?例如,我想将2013-04-16 05:30:05转换为2013年4月16日。实现此目的的正确方法是什么?
How to convert "yyyy-MM-ddTHH:mm:ss" into "dd MMM yyyy" format? For Instance, i want to convert 2013-04-16 05:30:05 into 16 April 2013. What is the correct method to achieve this?
推荐答案
首先, DateTime
没有格式。但是,如果您已经有一个表示 DateTime
的字符串,其格式为 yyyy-MM-ddTHH:mm:ss
并且要将其转换为格式为 dd MMM yyyy
的字符串日期,您需要先将其解析为 DateTime
。
First, a DateTime
has no format. But if you've already a string that represents a DateTime
with the format yyyy-MM-ddTHH:mm:ss
and you want to convert it to a string-date with format dd MMM yyyy
you need to parse it to DateTime
first.
因此使用 DateTime.ParseExact
:
DateTime dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null);
现在您可以使用 DateTime.ToString
:
string result = dt.ToString("dd MMM yyyy");
请注意,您需要传递其他 CultureInfo
DateTimeFormat $ c进行解析,则将对象指向 ParseExact
/ ToString
$ c>而不是当前的值(强制用英语月份的名称代替德语: dt.ToString( dd MMM yyyy,CultureInfo.InvariantCulture)
)。
Note that you need to pass a different CultureInfo
object to ParseExact
/ToString
if you want to parse with another DateTimeFormat
than your current (f.e. force english month names instead of german: dt.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)
).
这篇关于C#DateTime从yyyy-MM-ddTHH:mm:ss转换为dd MMM yyyy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!