Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c# - Get Date from String

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will extract, parse and print all dates in the input text:

var regex = new Regex(@"d{2}.d{2}.d{4}");
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(@"d{2}.d{2}.d{4}");
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...