Luis
Luis

Reputation: 2715

Get Datetimes from string

How can i get this 2 dates in this string?

FROM 2011-08-01 00:00 TO 2011-08-31 23:59 (Local Time) 2011-07-15 20:43

I want this date 2011-08-01 00:00 and 2011-08-31 23:59

Upvotes: 0

Views: 82

Answers (3)

Kev Ritchie
Kev Ritchie

Reputation: 1647

This should give you what you need (I've made the assumption that the string will always be in this format - so there is no error handling):

string text = "FROM 2011-08-01 00:00 TO 2011-08-31 23:59 (Local Time) 2011-07-15 20:43";

Regex r = new Regex(@"(?<=FROM)(.*?)(?=\()",
                  RegexOptions.Singleline | RegexOptions.IgnoreCase);

string[] dates = r.Split(text).GetValue(1).ToString().Trim().Split(' ');

string date1 = dates[0].ToString() + " " + dates[1].ToString();
string date2 = dates[3].ToString() + " " + dates[4].ToString();

Upvotes: 1

Jack
Jack

Reputation: 1525

This ought to do it:

    var dateRegex = @"\d{4}-\d{2}-\d{2} \d{2}:\d{2}";
    var regex = new Regex(@"FROM (" + dateRegex + @") TO (" + dateRegex + @") \(Local Time\) .*$");
    var text = @"FROM 2011-08-01 00:00 TO 2011-08-31 23:59 (Local Time) 2011-07-15 20:43";
    var match = regex.Match(text);
    if (match.Success)
    {
        Console.WriteLine("1: " + match.Groups[1].Value.ToString());
        Console.WriteLine("2: " + match.Groups[2].Value.ToString());
    }

Upvotes: 1

Joshua Honig
Joshua Honig

Reputation: 13215

Date 1: @"(?<=FROM )\d{4}-\d{2}-\d{2} \d{2}:\d{2}"

Date 2: @"(?<=TO )\d{4}-\d{2}-\d{2} \d{2}:\d{2}"

Upvotes: 2

Related Questions