我正在尝试将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失败了。我做错了什么?
答案 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);
}