Barak Rosenfeld
Barak Rosenfeld

Reputation: 337

string format of Date

I am trying to convert from a log file date format to an object dateTime

however I cannot find the string format to use in order to convert it?

can someone please help me with the format:

log file line: - Started 28/12/2014 16:53:47.48 "

my code:

 string pattern1 = @"(\d+)[/](\d+)[/](\d+)";
 Match match1 = Regex.Match(lineOfLog, pattern1, RegexOptions.IgnoreCase);
 if (match1.Success)
 {
   string dateFormat = "dd/MM/yyyy HH:mm:ss.zzz";
   string dateString = match1.Groups[1].Value;
   DateTime date = new DateTime();
   try
   {
    date = DateTime.ParseExact(dateString, dateFormat, CultureInfo.InvariantCulture);
   }

    catch
    {

    }

  }

exception: "string was not recognized as a valid date Time

Upvotes: 1

Views: 241

Answers (1)

Chris
Chris

Reputation: 5514

Three issues here:

  • the regex doesn't capture the entire date and time
  • you're just getting one part of the regex result (i.e. you're getting a single group instead of the value for the entire match)
  • your format string uses zzz when it should be FF for hundredths or FFF for thousands

Try something like this:

string lineOfLog = "- Started 28/12/2014 16:53:47.48";
string dateFormat = "dd/MM/yyyy HH:mm:ss.FF";           
string pattern1 = @"(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+)\.(\d+)";

Match match1 = Regex.Match( lineOfLog, pattern1, RegexOptions.IgnoreCase );
if( match1.Success )
{
    var dateString = match1.Value; // note the change here
    var d = DateTime.ParseExact( dateString, dateFormat, CultureInfo.InvariantCulture );
}

Note that you could omit the ()'s completely, they don't really do any good, but they do make the regex easier to read (IMHO).

Upvotes: 6

Related Questions