Reputation: 337
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
Reputation: 5514
Three issues here:
zzz
when it should be FF
for hundredths or FFF
for thousandsTry 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