如何将诸如2009-05-08 14:40:52,531这样的字符串转换为DateTime?


当前回答

String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);

这个给了你

2019-08-17 11:14:49.000

其他回答

试试这个

DateTime myDate = DateTime.Parse(dateString);

一个更好的方法是:

DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
    // handle parse failure
}

你想快点吗?

假设您有一个格式为yyMMdd的日期。

我发现转换它的最快方法是:

var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000, 
(s[2] - '0') * 10 + s[3] - '0', 
(s[4] - '0') * 10 + s[5] - '0')

只需根据您选择的日期格式选择索引。如果你需要速度,你可能不介意函数的“非泛型”方式。

此方法所需时间约为以下操作所需时间的10%:

var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);

你基本上有两个选择。DateTime.Parse()和DateTime.ParseExact()。

第一个在语法方面非常宽容,将以许多不同的格式解析日期。它对可能以不同格式出现的用户输入很有帮助。

ParseExact将允许您指定用于解析的日期字符串的确切格式。如果您的字符串总是使用相同的格式,那么使用这个是很好的。通过这种方式,您可以轻松地检测出与预期数据的任何偏差。

你可以这样解析用户输入:

DateTime enteredDate = DateTime.Parse(enteredString);

如果你有一个特定的字符串格式,你应该使用另一种方法:

DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);

“d”代表短日期模式(更多信息请参阅MSDN), null指定当前区域性应用于解析字符串。

string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);

//////// this methods convert string value to datetime
///////// in order to print date

Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);

如果您不确定输入值,也可以如下所示使用DateTime.TryParseExact()。

DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
    return outputDateTimeValue;
}
else
{
    // Handle the fact that parse did not succeed
}