从字符串中提取日期值 [英] Extracting a Date value from a string
问题描述
论坛.
我的代码从 excel 文件中读取并在变量textContainingDate"中获取以下字符串:
员工过滤器:所有员工;时间输入日期:01/07/2016-01/07/2016;例外:所有例外"
我想做的是从字符串中提取日期值.尽管有两个日期要读作日期范围,但这两个日期将始终相同.我的想法是,无论哪种情况,我都会对我遇到的第一次约会感到满意.
var dateTime = DateTime.ParseExact(textContainingDate, "MM/dd/yyyy", CultureInfo.CurrentCulture);
我尝试使用上述语句,这些语句是我从其他 stackoverflow 问题和 Google 搜索的文章中拼凑而成的.根据我的阅读,我认为它失败了,因为它只需要一个日期字符串.
对于解决方案和/或阅读文本以找到解决方案的方向的任何建议表示赞赏.
您可以使用
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.
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:
这篇关于从字符串中提取日期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!