MyException - 我的异常网
当前位置:我的异常网» C# » 求字符串"20070723122743"转入时间的最快

求字符串"20070723122743"转入时间的最快方法

www.MyException.Cn  网友分享于:2013-12-26  浏览:5次
求字符串"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);
挺好的!

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有