C # How to convert irregular date and time String to DateTime?

I have a program that converts an irregular date and time string to a DateTime system.

However, since the system does not recognize irregular strings, the .ParseExact, toDateTime, and TryParse methods did not work.

There are only 2 types of date strings that a program should convert:

 Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010

Note that a single date has a double spacing, which I used the .replace method to convert a single date to Thu Dec 09 05:12:42 2010.

Can someone consult on codes? Thank!

Codes:

        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
+3
source share
3 answers

, .NET( TryParseExact ):

DateTime result;
string dateToParse = "Thu Dec  9 05:12:42 2010";
string format = "ddd MMM d HH:mm:ss yyyy";

if (DateTime.TryParseExact(
    dateToParse, 
    format,
    CultureInfo.InvariantCulture, 
    DateTimeStyles.AllowWhiteSpaces, 
    out result)
)
{
    // The date was successfully parsed => use the result here
}
+5

, .

Regex ,

((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})
0

This is an example of code that you can try:

        var str = "Thu Dec  9 06:45:58 2010";
        if (str.IndexOf("  ") > -1)
        {
            str = str.Replace("  ", " ");
            DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
        }
        else
        {
            DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
        }
0
source

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


All Articles