3

I have a program which converts a irregular date and time string into a system DateTime.

However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.

There are only 2 types of date time strings that the program needs to convert:

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

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

May someone please advise on the codes? Thanks!

The 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 Answers 3

6

I would really avoid regex and use what's already built-in .NET (TryParseExact method and date formats):

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
}
Sign up to request clarification or add additional context in comments.

6 Comments

@Darin: The regex is only there to extract the date from a larger string. See his earlier question.
@AgentConundrum, from what I can see he is using regex to replace the whitespaces in the original string, adding 0 at the beginning of the day, etc... stuff that's not necessary with a correct format string.
@Darin: You're right. I glossed right over the second regex. Sorry about that.
@Darin the first regex has actually noting to do with the conversion of the time date I'll remove it....
@JavaNoob, the point here is that you should remove all regexes and never use them for such a task :-)
|
0

You should capture the parts of your datetime into capture groups in the Match Object, then reconstitute them any way you want.

You can use this Regex statement with named groups to make it easier

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

Comments

0

This is sample code which 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);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.