将字符串解析为C#中的DateTime对象

时间:2013-04-15 16:48:23

标签: c# string parsing c#-4.0 datetime

我正在尝试将String日期和时间解析为单个.NET DateTime对象。我有以下代码:

string dtObjFormat = "dd MMM YYYY HH:mm";
string mydatetimemash = e.Date + " " + e.Time; // this becomes 25 May 2013 10:30
DateTime dt;

if (DateTime.TryParseExact(mydatetimemash, dtObjFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
} else 
{
    dt = DateTime.Now;
    Console.WriteLine(dt);
}

但是TryParseExact总是为我返回false,这意味着Parse失败了。我做错了什么?

1 个答案:

答案 0 :(得分:2)

你的Y需要小写,如下:

string dtObjFormat = "dd MMM yyyy HH:mm";
string mydatetimemash = e.Date + " " + e.Time; // this becomes 25 May 2013 10:30
DateTime dt;

if (DateTime.TryParseExact(mydatetimemash, dtObjFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
} else 
{
    dt = DateTime.Now;
    Console.WriteLine(dt);
}