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 questi
CultureInfo enUS = new CultureInfo( "en-US" );
DateTime dt = DateTime.ParseExact( "Tue Jan 20 19:47:43 GMT 2009", "ffffd MMM dd HH:mm:ss 'GMT' yyyy", enUS, DateTimeStyles.None );
Console.WriteLine( dt.ToString() );
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", "ffffd MMM dd H:mm:ss \"GMT\" yyyy", enUS, System.Globalization.DateTimeStyles.NoCurrentDateDefault , out dt ))
{
Console.WriteLine(dt.ToString() );
}
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 = "ffffd 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);
}