tags:

views:

337

answers:

10

I'm using .NET 3.5 and I have a date that comes in as string in the following format:

Tue Jan 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.

Edit: I forgot to mention that I've already tried using DateTime.Parse and Convert.ToDateTime. None of those worked.

A: 
DateTime.Parse("Tue Jan 20 20:47:43 GMT 2009")
Dustin Laine
Doesn't work, forgot to mention so in the question
Jonas Stawski
this does not parse
Pharabus
+2  A: 
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

Using 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.

Atømix
This doesn't help me. It won't parse and it will return false leaving me back where I started
Jonas Stawski
edited. Have you tried playing around with the format string?
Atømix
Now it works and I like it. It ignores the GMT, do you know what the pattern is for GMT so we can include it?
Jonas Stawski
There isn't any I could find. Here's a cheat sheet if you like: http://blog.stevex.net/string-formatting-in-csharp/
Atømix
Solved the issue by doing dt.ToLocalTime()
Jonas Stawski
Yep. Also more info here: http://msdn.microsoft.com/en-us/library/91hfhz89.aspx
Atømix
A: 

You could use Convert.ToDateTime

Marek Karbarz
wow, a minus one - care to elaborate?
Marek Karbarz
yes, I was elavorating, but my comment failed to insert. This doesn't work. Read my edit
Jonas Stawski
A: 

Try to do a DateTime.Parse("Tue Jan 20 20:47:43 GMT 2009") and see if it accepts it.

Here's a good link for custom DateTime formatting.

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

I hope that helps.

Dan H
This doesn't work
Jonas Stawski
+3  A: 

Move the year from the end to the beginning and you can parse that string without a problem.

2009 Tue Jan 20 20:47:43 GMT

Is a valid date format. The original string is not.

string input = "Tue Jan 20 20:47:43 GMT 2009";
input = input.Substring(input.Length - 4) + " " + input.Substring(0, input.Length - 4).Trim();

DateTime date;
DateTime.TryParse(input, out date);
Console.WriteLine(date);
Anthony Pegram
Oh sure contribute to the y10k problem.
Scott Chamberlain
+1 for correctness and the addition of sample code
Jonas Stawski
@jtawski, also look at the TryParseExact examples that have been edited into answers below. They could be useful.
Anthony Pegram
Nice workaround. Although you may want to add a trim on the input var to ensure it works as planned. In addition, if you know the exact format of the date, using the exact format is more efficient than string manipulation. :-) ( dunno who downvoted, though)
Atømix
I just did and I'm giving them +1 as well, if we can figure out the GMT problem then it will be the perfect solution
Jonas Stawski
@Atomiton, of course it can be better formatted. Also, I honestly was not cognizant of the TryParseExact method at the time. It's good to learn.
Anthony Pegram
@Anthony. Nah. It was a good solution. Programming, after all, is about finding solutions to problems and there are always more than one way to approach the problem. That's what I love about SO... different approaches to problems. On the other hand, in this case... I think specifying the format is a more explicit way to go and more readable going forward.
Atømix
+5  A: 

You can use the DateTime.TryParseExact() method with a suitable format string. 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() );
        }
TLiebe
+1: Much better than accepted answer, as it demonstrates how to handle wonky date formats, unfortunately a pretty common occurrence.
RedFilter
it is better than accepted answer. I'm changing it
Jonas Stawski
read comments on answer posted by Atomiton
Jonas Stawski
Thanks OrbMan. I've become very familiar with the DateTime.TryParseExact() method from dealing with a client that thinks they should be able to enter a date in a dozen or so different formats. I actually use the overloaded version that accepts an array of string formats.
TLiebe
A: 

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.

HTH

Raja
returns false and i'm back where i started
Jonas Stawski
A: 
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() );
OmegaMan
+2  A: 

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. Exceptions will only tell you that "String was not recognized as a valid DateTime", which doesn't really help. It had to figure out the date format specifiers myself because I didn't find them in MSDN.

The "en-US" locale is necessary, I guess, because your date format uses English abbreviations like "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 (e.g. If-Modified-Since: Wed, 08 Dec 2004 13:25:25 GMT).

AndiDog
I should add that I wasn't able to cope with the "GMT", so I replaced it with "+00" which makes sure that at least the GMT timezone can be parsed correctly.
AndiDog
+1 for dealing with GMT.
Jonas Stawski
A: 

You can use DateTime.ParseExact or DateTimeOffset.ParseExact to specify the format of the date string.

Although, I wasn't able to quickly figure out how to match the timezone specifier (i.e. 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. Although, none of those solutions were from StackOverflow, so who knows how good they are.

Here's a short example I wrote, with the "GMT" stripped from the date string trying to be converted. If you could replace the timezone with the offset, add "zzz" to the format string. For the parse other formats, heres the MSDN page Custom Date and Time Format Strings that lists them all.

// 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);
}
Adam Porad