Parsing Extra Characters from Datetime

Hi I have the following code that reads a date from a file.

using (var reader = new StreamReader(@"C:\myfile.txt")) 
{
    bool found= false;
    while (!reader.EndOfStream) 
  {
        var line = reader.ReadLine().Trim();

        if (found && line.EndsWith("Test")) 
        {
            var fordDate = DateTime.Parse(line.Substring(0, 19));
            Console.WriteLine("Test Date: {0}", fordDate);
            break;
        }
   }
 }

The problem is that it gives an error when the date has another text associated with it. for instance

\r\n2013-03-03 12:22:02 

I am trying to change it so that the code can remove "\ r \ n" or any other text from it and just get the date part.

+5
source share
3 answers

You must use regular expressions

If your dates always have the same format, you can easily write a regular expression that will extract dates from separate lines and cut something else on each side. To understand the regex, it should look like this:

\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}

, 0000-00-00 99:99:99, , , . , , , . ( ) ( , YYYY-MM-DD, YYYY-DD-MM):

[12]\d{3}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])\s(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)

1000 2999 01-12 01-31 00:00:00 23:59:59.

, , (date) , , , .

Regex rx = "(?<date>[12]\d{3}-(?:0\d|1[0-2])-(?:0[1-9]|[12]\d|3[01])\s(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)).*Test$";
if (rx.Text(line))
{
    Match m = rx.Match(line);
    // no need to use TryParse as regex assures correct formatting
    fordDate = DateTime.Parse(m.Groups["date"]);
}

, , Test, .

+3

:

string lineAfterReplace = line.Replace("\t", "").Replace("\r", "").Replace("\n", "");

@J. - TryParse MSDN

- :

if (DateTime.TryParse(dateString, out dateValue))
{
   /* it was parsed without errors */
}
+1

Edit:

var fordDate = DateTime.Parse(line.Substring(0, 19));

To:

var fordDate = DateTime.Parse(line.Substring(0, 19).Trim());

If each DateTime String is located on one line in a file, it is best to use:

var fordDate = DateTime.Parse(line.Trim());
0
source

All Articles