Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a Date value from a string

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.

like image 658
HappyCoding Avatar asked Sep 09 '26 05:09

HappyCoding


2 Answers

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

like image 151
wingerse Avatar answered Sep 11 '26 19:09

wingerse


 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";
  }
like image 25
Adeel Kamran Avatar answered Sep 11 '26 18:09

Adeel Kamran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!