0

I'm working with a log file that is giving me a date string that looks like so:

09/Feb/2012:00:38:48

I've been looking at different pages online about converting dates such as the MSDN site, but none of them show a date quite like this one.

Do I need to manually reformat the string to look similar to:

2012-02-09T00:38:48.0000000

Or is there a way to have this actually converted?

2 Answers 2

6

You can use DateTime.TryParseExact to parse a string to a DateTime from any format you specify. There's a load of examples the bottom of this MSDN ref.

Sign up to request clarification or add additional context in comments.

3 Comments

@MordecaiX7: You want MMM - see my example.
Use MMM which represents the shorthand month name as per your case. Check out the full reference for the options for formatting here: msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Ah I didn't realize I could tell the parser what format the date is in. Thanks.
3

As stated by AdaTheDev, DateTime.TryParseExact is the way forward here. As per the MSDN page on "custom date and time format strings" you want MMM for the abbreviated month name.

using System;
using System.Globalization;

class Test
{
    static void Main() 
    {
        string text = "09/Feb/2012:00:38:48";
        DateTime value;
        if (DateTime.TryParseExact(text, "dd/MMM/yyyy:HH:mm:ss",
                                   CultureInfo.InvariantCulture,
                                   DateTimeStyles.None,
                                   out value))
        {
            Console.WriteLine("Success! {0}", value);
        }
        else
        {
            Console.WriteLine("Failed");
        }
    }
}

Note the use of CultureInfo.InvariantCulture - it doesn't look like you should use the current culture for example.

(Of course, you could use Noda Time instead ;)

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.