Karen Payne
Karen Payne

Reputation: 5117

Extract DateTime from string

When looping through elements in a List<string> I want to extract the first date time.

This is a sample line where in this case month is a single digit, month can also be a double digit e.g. 12 but not say 01.

string line = "\\\\SomeServer\\HTTP\\demo1\\index.cfm 4 KB CFM " + 
              "File 2/19/2019 3:48:21 PM " + 
              "2/19/2019 1:05:53 PM 2/19/2019 1:05:53 PM 5";

The expected result would be

2/19/2019 3:48:21 PM

I have looked at various regular expression code sample here, the following is one which properly handles single digit months only and does not return the time portion for the date (as I don't know what pattern to use).

var line = "\\\\SomeServer\\HTTP\\FolderName\\index.cfm 4 KB CFM " +
           "File 02/19/2019 3:48:21 PM " +
           "2/19/2019 1:05:53 PM 2/19/2019 1:05:53 PM 5";

var match = Regex.Match(line, 
    @"\d{2}\/\d{2}\/\d{4}");

var dateValue = match.Value;
if (!string.IsNullOrWhiteSpace(dateValue))
{

    var dateTime = DateTime.ParseExact(dateValue, 
        "MM/dd/yyyy", 
        CultureInfo.CurrentCulture);

    Console.WriteLine(
        dateTime.ToString(CultureInfo.InvariantCulture));
}

In closing, I've looked at recommended question lite up when posting this question and have virtually no expertise creating regular expressions. I appreciate any recommendations and/or code samples to get me in the right direction.

Upvotes: 1

Views: 406

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use

\b\d{1,2}/\d{1,2}/\d{4}\s\d{1,2}:\d{2}:\d{2}\s?[AP]M\b

See the regex demo. The Regex.Match will get you the first match.

Details

  • \b - word boundary
  • \d{1,2}/\d{1,2}/\d{4} - one or two digits, /, one or two digits, /, four digits
  • \s - a whitespace
  • \d{1,2}:\d{2}:\d{2} - 1 or 2 digits, :, 2 digits, :, 2 digits
  • \s? - an optional whitespace
  • [AP]M - AM or PM
  • \b - word boundary.

Upvotes: 2

Related Questions