Converting a String to DateTime

如何将字符串(如2009-05-08 14:40:52,531转换为DateTime


由于您正在处理基于24小时的时间,并且用逗号分隔秒分数,所以我建议您指定一种自定义格式:

DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);

You have basically two options for this. DateTime.Parse() and DateTime.ParseExact() .

The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.

ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.

You can parse user input like this:

DateTime enteredDate = DateTime.Parse(enteredString);

If you have a specific format for the string, you should use the other method:

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

"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.


try this

DateTime myDate = DateTime.Parse(dateString);

a better way would be this:

DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
    // handle parse failure
}
链接地址: http://www.djcxy.com/p/25186.html

上一篇: 在Python中将整数转换为字符串?

下一篇: 将字符串转换为DateTime