3

Forum.

My code reads from an excel file and gets the following string in a variable 'textContainingDate':

"Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions"

What I would like to do is extract the date value from the string. Although there are two dates to be read as a date range, the two dates will always be the same. My thought is, regardless of the scenario, I will be satisfied with the first date I come across.

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

I tried using the above statement, which I pieced together from other stackoverflow questions and Googled articles. From what I have read, I believe it fails because it is expecting only a date string.

Any advising on a solution and/or direction towards what text to read to find a solution is appreciated.

HappyCoding
  • 641
  • 16
  • 36
  • Use regular expression to get date strings, and then use your method to converting it to `DateTime`. – Aleksandr Ivanov Jan 20 '16 at 22:37
  • Is the text preceding dates always the same? If that's the case you can use simple substring to cut the date – Yuriy Galanter Jan 20 '16 at 22:44
  • `DateTime.ParseExact()` method exactly parses string like `01/20/2012` into a date object. You are trying to convert the whole string which contains a date value into a date object which is not possible. Extract the date string using regular expression and parse that into a date object. – h-rai Jan 20 '16 at 22:52

2 Answers2

8

You can use Regex.Match to get the first date string you meet. This method returns the first substring that matches a regular expression pattern in an input string.

string stringWithDate = "Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions";
Match match = Regex.Match(stringWithDate, @"\d{2}\/\d{2}\/\d{4}");
string date = match.Value;
if (!string.IsNullOrEmpty(date)) {
    var dateTime = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.CurrentCulture);
    Console.WriteLine(dateTime.ToString());
}

What the regular expression \d{2}\/\d{2}\/\d{4} does:
enter image description here

wingerse
  • 3,670
  • 1
  • 29
  • 61
1
 var regex = new Regex(@"\d{2}\/\d{2}\/\d{4}");
 foreach (Match m in regex.Matches(line))
 {
  DateTime dt;
  if (DateTime.TryParseExact(m.Value, "MM/dd/yyyy", null, DateTimeStyles.None, out dt))
  remittanceDateArr[chequeNo - 1] = dt.ToString("MM/dd/yyyy");                                   
  rtbExtract.Text = rtbExtract.Text + remittanceDateArr[chequeNo - 1] + "\n";
  }
Adeel Kamran
  • 103
  • 7