gpt4 book ai didi

c# - 从字符串中提取日期值

转载 作者:行者123 更新时间:2023-12-01 22:25:50 24 4
gpt4 key购买 nike

论坛。

我的代码从 excel 文件读取并在变量“textContainingDate”中获取以下字符串:

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

我想做的是从字符串中提取日期值。虽然有两个日期要读作一个日期范围,但是这两个日期总是相同的。我的想法是,无论情况如何,我都会对遇到的第一次约会感到满意。

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

我尝试使用上述语句,它是我从其他 stackoverflow 问题和 Google 搜索文章中拼凑而成的。根据我的阅读,我认为它失败了,因为它只需要一个日期字符串。

任何关于解决方案的建议和/或阅读哪些文本以找到解决方案的方向都值得赞赏。

最佳答案

您可以使用 Regex.Match获取您遇到的第一个日期字符串。此方法返回与输入字符串中的正则表达式模式匹配的第一个子字符串。

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());
}

正则表达式 \d{2}\/\d{2}\/\d{4} 的作用:
enter image description here

关于c# - 从字符串中提取日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34911874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com