Search code examples
c#.netregexstring-parsing

How to get date from this string?


I have this string:

\tid <01CA4692.A44F1F3E@blah.blah.co.uk>; <b>Tue, 6 Oct 2009 15:38:16</b> +0100

and I want to extract the date (emboldened) to a more usable format, e.g. 06-10-2009 15:38:16

What would be the best way to go about this?


Solution

  • Regex might be overkill. Just Split on ';', Trim(), and call Date.Parse(...), It will even handle the Timezone offset for you.

    using System;
    
    namespace ConsoleImpersonate
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                string str = "\tid 01CA4692.A44F1F3E@blah.blah.co.uk; Tue, 6 Oct 2009 15:38:16 +0100";
                var trimmed = str.Split(';')[1].Trim();
                var x = DateTime.Parse(trimmed);
    
            }
        }
    }