Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top