如何将异常格式的字符串转换为datetime [英] How to convert string with unusual format into datetime
问题描述
我使用的是.NET 3.5,我的日期是以下列格式输入的字符串:
I'm using .NET 3.5 and I have a date that comes in as string in the following format:
20:47:43 GMT 2009
Tue Jan 20 20:47:43 GMT 2009
第一个问题,该格式的名称是什么?第二个问题,将这个字符串转换成datetime最简单和最清晰的方法是什么?如果可能,我希望能够使用.net API / Helper方法。
First question, what is the name of that format? Second question, what's the easiest and clearest way to convert this string into a datetime? I would love to be able to use a .net API/Helper method if possible.
编辑:我忘了提到我已经尝试使用DateTime.Parse和Convert.ToDateTime。
I forgot to mention that I've already tried using DateTime.Parse and Convert.ToDateTime. None of those worked.
推荐答案
可以使用适当的格式字符串的DateTime.TryParseExact()方法。请参阅 here
You can use the DateTime.TryParseExact() method with a suitable format string. See here
编辑:尝试这样:
DateTime dt;
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
if ( DateTime.TryParseExact( "Tue Jan 20 20:47:43 GMT 2009", "ddd MMM dd H:mm:ss \"GMT\" yyyy", enUS, System.Globalization.DateTimeStyles.NoCurrentDateDefault , out dt ))
{
Console.WriteLine(dt.ToString() );
}
这篇关于如何将异常格式的字符串转换为datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!