How to convert a string with an unusual format to datetime

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

Tuesday January 20 20:47:43 GMT 2009

First question, what is the name of this format? Second question, what is the easiest and clearest way to convert this string to datetime? I would like to be able to use the .net API / Helper API, if possible.

Edit: I forgot to mention that I was already trying to use DateTime.Parse and Convert.ToDateTime. None of them worked.

+3
source share
9 answers

You can use the DateTime.TryParseExact () method with a suitable format string. See here

EDIT: - :

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

TryParseExact, DateTime

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 */
 }    

, . , GMT, .

+2

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"));

API DateTime . , "String DateTime", . , MSDN.

"en-US" , , , "Tue".

, , . , , HTTP (, If-Modified-Since: Wed, 08 Dec 2004 13:25:25 GMT).

+2

DateTime.Parse( "Tue Jan 20 20:47:43 GMT 2009" ) , .

DateTime.

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

, .

0

:

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

. If true, .

0
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() );
0

DateTime.ParseExact DateTimeOffset.ParseExact, .

, , (.. GMT). Google, , , , - , +/-, - . StackOverflow, , .

, , "GMT", , . , "zzz" . , 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);
}
0
source
DateTime.Parse("Tue Jan 20 20:47:43 GMT 2009")
-1
source

Source: https://habr.com/ru/post/1740516/


All Articles