tags:

views:

166

answers:

4

I am experimenting with C# w/ a C++ background. I have been playing with DateTime objects and find them pretty useful so far, especially the ParseExact() function!

Taking the idea of DateTime.ParseExact() one step further, I want to extract the DateTime from a string (a log entry) which will have other info in it, with variable lengths on both ends of the DateTime info.

I believe I can accomplish what I need with regular expressions, substring, and ParseExact, but I am hoping for an easier solution (just like how ParseExact turned out to be a very easy alternative to a longer, manual method). Does anyone have any suggestions?

EDIT: I don't have control over the log format, and while the format of the date and time in the log is fixed, its position is not. Thanks for the feedback! I think I will probably have to use regular expresssions!

+1  A: 

Both Parse and ParseExact require having only actual date in parameter.

If you have log e.g.:

20091229T213000 Something Something

you will need to first extract date from it (with e.g. substring) and only then you can parse it to get DateTime.

Josip Medved
A: 

You don't need both regular expressions and substrings. If the date is in a fixed position in the string, then using string.Substring is very straightforward and is the way to go. If you are having to identify the position in the string, then a regular expression may be the way to go.

In either case, you must extract the date string first before passing to ParseExact.

David M
A: 

If you have control of the log format, then you can write the DateTime in an easy-to-parse format - for example, delimit it with a specific tag that isn't used elsewhere - e.g. [...]

Then it'll be trivial to extract the relevant text (e.g. with string.IndexOf("[") and string.Substring()) and then fling it at DateTime.ParseExact().

Jason Williams
A: 

You won't find it in the standard library, but if you know your datetime format or log record format nothing prevents you from writing it yourself.

You don't necessarily need regular expressions. Log records are often separated by space, tab, ;, | or other symbol and you can split each record into parts using string.Split and then parse date using Parse or ParseExact.

yu_sha