从String获取日期 [英] Get Date from String
本文介绍了从String获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,我是一个字符串...这是一个Stackoverflowquestion !!这是一个日期:16.03.2013,02:35是的,纯文本blah blah ..-。
这是另一个字符串!:) 22.11.2012。它的日期你看到
这里我们有2个日期,23.12.2012和14.07.2011
从字符串中获取这些日期是最好最快的方式(在$ code > DateTime )?
(只有字符串中第一个发生日期)
返回:
String 1:16.03.2013(作为DateTime)
字符串2:22.11.2012( )
String 3:23.12.2012()
所以我会调用一个方法如下所示:
DateTime date1 = GetFirstDateFromString(string1);
解决方案
这将提取,解析和打印所有日期输入文本:
var regex = new Regex(@\b\d {2} \.d {2} .\d {4} \b);
foreach(在regex.Matches(inputText)中匹配m)
{
DateTime dt;
if(DateTime.TryParseExact(m.Value,dd.MM.yyyy,null,DateTimeStyles.None,out dt))
Console.WriteLine(dt.ToString());
}
现在,如果你只想要第一个日期,你可以这样做: / p>
static DateTime? GetFirstDateFromString(string inputText)
{
var regex = new Regex(@\b\d {2} \.\d {2} .\d {4} \b );
foreach(在regex.Matches(inputText)中匹配m)
{
DateTime dt;
if(DateTime.TryParseExact(m.Value,dd.MM.yyyy,null,DateTimeStyles.None,out dt))
return dt;
}
返回null;
}
请注意,该方法返回一个可空的 DateTime
,所以当字符串不包含日期时,它可以返回null。
Lets say I have one of following strings:
"Hello, I'm a String... This is a Stackoverflowquestion!! Here is a Date: 16.03.2013, 02:35 and yeah, plain text blah blah..-."
"This the other string! :) 22.11.2012. Its a Date you see"
"Here we have 2 Dates, 23.12.2012 and 14.07.2011"
What would be the best and fastest way to get these dates from the string (in DateTime
)?
(Only First occured Date in String)
Desirable Returns:
String 1: 16.03.2013 (as a DateTime)
String 2: 22.11.2012 (" ")
String 3: 23.12.2012 (" ")
So I would call a method something like:
DateTime date1 = GetFirstDateFromString(string1);
解决方案
This will extract, parse and print all dates in the input text:
var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
foreach(Match m in regex.Matches(inputText))
{
DateTime dt;
if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
Console.WriteLine(dt.ToString());
}
Now, if you just want the first date, you can do that:
static DateTime? GetFirstDateFromString(string inputText)
{
var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
foreach(Match m in regex.Matches(inputText))
{
DateTime dt;
if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
return dt;
}
return null;
}
Note that the method returns a nullable DateTime
, so that it can return null when the string contains no date.
这篇关于从String获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文