Skip to main content
 首页 » 编程设计

c#之在 C# 中使用正则表达式解析日期

2024年02月03日32txw1958

我正在开发 C# 应用程序,我得到一个包含日期或部分日期的字符串,我需要获取该字符串的日、月和年。例如:

string example='31-12-2010' 
string day = Regex.Match(example, "REGULAR EXPRESSION FOR DAY").ToString(); 
string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() 
string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() 
 
day = "31" 
month = "12" 
year = "2010" 
 
ex2:  
string example='12-2010' 
 
string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() 
string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() 
 
month = "12" 
year = "2010" 

有什么想法吗?

请您参考如下方法:

不要为此使用正则表达式。 而是使用

DateTime temp = DateTime.Parse(example); 

现在有很多有用的属性供您使用。 temp.Day 例如