日期:2014-05-19  浏览次数:20767 次

求字符串"20070723122743",转为时间的最快方法
自己做了一个效率不高,字符串转为时间后对应为2007-7-23   12:27:43   ,谢谢!

------解决方案--------------------
DateTime.TryParse()
===
using System;
using System.Globalization;

namespace Parse
{
class Class1
{
public static void Main(string[] args)
{
// Assume the current culture is en-US.
// The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds.

string myDateTimeValue = "2/16/1992 12:15:12 ";
DateTime myDateTime = DateTime.Parse(myDateTimeValue);
Console.WriteLine( "1) myDateTime = {0} ", myDateTime);

// Reverse month and day to conform to a different culture.
// The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds.

IFormatProvider culture = new CultureInfo( "fr-FR ", true);
string myDateTimeFrenchValue = " 16/02/1992 12:15:12 ";
DateTime myDateTimeFrench =
DateTime.Parse(myDateTimeFrenchValue,
culture,
DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine( "2) myDateTimeFrench = {0} ", myDateTimeFrench);

// The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds.

string[] expectedFormats = { "G ", "g ", "f " , "F "};
myDateTimeFrench =
DateTime.ParseExact(myDateTimeFrenchValue,
expectedFormats,
culture,
DateTimeStyles.AllowWhiteSpaces);
Console.WriteLine( "3) myDateTimeFrench = {0} ", myDateTimeFrench);
}
}
}
/*
This example yields the following results:

1) myDateTime = 2/16/1992 12:15:12 PM
2) myDateTimeFrench = 2/16/1992 12:15:12 PM
3) myDateTimeFrench = 2/16/1992 12:15:12 PM
*/


------解决方案--------------------
string S = "20070723122743 ";
DateTime vDateTime = DateTime.ParseExact(S, "yyyyMMddHHmmss ", null,
System.Globalization.DateTimeStyles.None);
Console.WriteLine(vDateTime);

------解决方案--------------------
不过有更简单的重载
string S = "20070723122743 ";
DateTime dt = DateTime.ParseExact(S, "yyyyMMddHHmmss ", null);
------解决方案--------------------
就这个呀
DateTime dt = DateTime.ParseExact( "20070723122743 ", "yyyyMMddhhmmss ", System.Globalization.CultureInfo.CurrentCulture);
挺好的!