简体   繁体   English

如何将具有异常格式的字符串转换为datetime

[英]How to convert string with unusual format into datetime

I'm using .NET 3.5 and I have a date that comes in as string in the following format: 我正在使用.NET 3.5,我的日期以字符串形式出现,格式如下:

Tue Jan 20 20:47:43 GMT 2009 1月20日星期二20:47:43 GMT 2009

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. 如果可能的话,我希望能够使用.net API / Helper方法。

Edit: I forgot to mention that I've already tried using DateTime.Parse and Convert.ToDateTime. 编辑:我忘了提到我已经尝试过使用DateTime.Parse和Convert.ToDateTime。 None of those worked. 这些都没有奏效。

You can use the DateTime.TryParseExact() method with a suitable format string. 您可以将DateTime.TryParseExact()方法与合适的格式字符串一起使用。 See here 看到这里

EDIT: Try something like this: 编辑:尝试这样的事情:

        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 dt;
if(DateTime.TryParse("Tue Jan 20 20:47:43 GMT 2009", out dt)){
   /* Yay.. it's valid */
}

You can also use TryParseExact where you can specify the format of your DateTime 您还可以使用TryParseExact指定DateTime的格式

Using TryparseExact 使用TryparseExact

const string FORMAT = "ddd MMM dd HH:mm:ss \"GMT\" yyyy";
if (DateTime.TryParseExact("Tue Jan 20 20:47:43 GMT 2009", FORMAT, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out dt)) {
        /* is valid */
 }    

I believe that should work. 我认为应该有用。 Not sure if it will try to parse out the GMT though. 不确定它是否会尝试解析GMT。

There you go 你去吧

DateTime d = DateTime.ParseExact("Tue Jan 20 20:47:43 GMT 2009".Replace("GMT", "+00"), "ddd MMM dd H:mm:ss zz yyyy", new CultureInfo("en-US"));

The DateTime API and its documentation pretty much sucks. DateTime API及其文档非常糟糕。 Exceptions will only tell you that "String was not recognized as a valid DateTime", which doesn't really help. 例外只会告诉您“字符串未被识别为有效的DateTime”,这实际上没有帮助。 It had to figure out the date format specifiers myself because I didn't find them in MSDN. 它必须自己弄清楚日期格式说明符,因为我没有在MSDN中找到它们。

The "en-US" locale is necessary, I guess, because your date format uses English abbreviations like "Tue". 我想,“en-US”语言环境是必要的,因为您的日期格式使用英语缩写,如“Tue”。

Anyway, I can't tell you what the date format is called. 无论如何,我无法告诉你日期格式是什么。 It is pretty similar but not equal to a format used with HTTP (eg If-Modified-Since: Wed, 08 Dec 2004 13:25:25 GMT ). 它非常相似,但不等于HTTP使用的格式(例如, If-Modified-Since: Wed, 08 Dec 2004 13:25:25 GMT )。

您可以使用Convert.ToDateTime

Try to do a DateTime.Parse("Tue Jan 20 20:47:43 GMT 2009") and see if it accepts it. 尝试做一个DateTime.Parse(“Tue Jan 20 20:47:43 GMT 2009”)并看看它是否接受它。

Here's a good link for custom DateTime formatting. 这是自定义DateTime格式的一个很好的链接。

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

I hope that helps. 我希望有所帮助。

Try this: 尝试这个:

DateTime.TryParse(Tue Jan 20 20:47:43 GMT 2009", out objDt);

You need to give an output value. 您需要提供输出值。 Use If and if it returns true then its a valid date. 使用If和if返回true,然后是有效日期。

HTH HTH

CultureInfo enUS = new CultureInfo( "en-US" ); 

DateTime dt = DateTime.ParseExact( "Tue Jan 20 19:47:43 GMT 2009", "ddd MMM dd HH:mm:ss 'GMT' yyyy", enUS, DateTimeStyles.None );

Console.WriteLine( dt.ToString() );

You can use DateTime.ParseExact or DateTimeOffset.ParseExact to specify the format of the date string. 您可以使用DateTime.ParseExactDateTimeOffset.ParseExact指定日期字符串的格式。

Although, I wasn't able to quickly figure out how to match the timezone specifier (ie GMT). 虽然,我无法快速弄清楚如何匹配时区说明符(即GMT)。 A look at a few Google results, shows that most people who are trying to solve this are doing it heuristically -- making a list of all time zones and the offsets and then parsing the string and replacing the timezone specifier with the +/- offset, or some other sort of hackish approach. 看一下谷歌的一些结果,表明大多数试图解决这个问题的人都是以启发的方式做到这一点 - 制作所有时区和偏移的列表然后解析字符串并用+/-偏移替换时区说明符,或其他一些hackish方法。 Although, none of those solutions were from StackOverflow, so who knows how good they are. 虽然这些解决方案都不是来自StackOverflow,但谁知道它们有多好。

Here's a short example I wrote, with the "GMT" stripped from the date string trying to be converted. 这是我写的一个简短示例,其中“GMT”从试图转换的日期字符串中删除。 If you could replace the timezone with the offset, add "zzz" to the format string. 如果您可以使用偏移替换时区,请将“zzz”添加到格式字符串中。 For the parse other formats, heres the MSDN page Custom Date and Time Format Strings that lists them all. 对于解析其他格式,继承MSDN页面自定义日期和时间格式字符串列出所有格式

// Parse date and time with custom specifier.
string dateString = "Tue Jan 20 20:47:43 2009";
string format = "ddd MMM dd HH:mm:ss yyyy";
DateTime result;
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;

try
{
   result = DateTime.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}
DateTime.Parse("Tue Jan 20 20:47:43 GMT 2009")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM