Gilbert Williams
Gilbert Williams

Reputation: 1050

Retrieve DateTime objects from a certain string

I have the following string:

"23/09/2015 08:00\r\n            עד\r\n24/09/2015 08:00"

As you can see, we have two dates. One before the first \r\n and the other one after the second \r\n.

How can I retrieve DateTime objects from this string in C#? The only way I know is to use Substring but that retrieves the text after the first \r\n.

Upvotes: 1

Views: 35

Answers (3)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

This may help

 var stringValue = "23/09/2015 08:00\r\n            עד\r\n24/09/2015 08:00";

 var splitted = stringValue.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);

 var firstStringDate = splitted[0];
 var secondStringDate = splitted[2];

And to get the DateTime:

var firstDate = DateTime.ParseExact(splitted[0], "dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
var secondDate = DateTime.ParseExact(splitted[2], "dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);

Upvotes: 3

Matteo Umili
Matteo Umili

Reputation: 4017

Split and TryParse the strings:

static IEnumerable<DateTime> extractDates(string inputString)
{
    foreach (var item in inputString.Split(new string[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries))
    {
        DateTime dt;
        if(DateTime.TryParseExact(item, 
                                   "dd/MM/yyyy HH:mm",
                                   System.Globalization.CultureInfo.InvariantCulture,
                                   System.Globalization.DateTimeStyles.None, 
                                   out dt))
            yield return dt;
    }
}

Upvotes: 1

Philippe Par&#233;
Philippe Par&#233;

Reputation: 4418

I would use myString.Split("\r\n") like so:

string[] dates = myString.Split("\r\n");

foreach (var dateString in dates)
{
    DateTime dateTime;
    if (DateTime.TryParse(dateString, out dateTime))
    {
        //Use dateTime here
    }
}

Upvotes: 0

Related Questions