Reputation: 1567
My input is a string that represent machine's execution time and date. The problem is that this string is formatted badly therefore I can't use DateTime.Parse
to convert it to a DateTime
object.
Input example:
2014-01-07-15.26.46.000452
I need to convert it to something I can work with (replacing the last '-' with a space and the first 2 '.' with a ':') like so:
2014-01-07 15:26:46.000452
I figured I should use regex to solve this because I need to replace characters at specific locations so myString.Replace
won't do any good. Unfortunately, my knowledge of using regex is close to nothing and I couldn't find any examples to match my problem.
Can anyone help me solve this one out? (Also, I would like an explanation on how & why this regex works)
Upvotes: 0
Views: 63
Reputation: 156918
It doesn't look very pretty, but does the job:
string yourString = "2014-01-07-15.26.46.000452";
string newString = Regex.Replace(yourString, @"(\d+)-(\d+)-(\d+)-(\d+).(\d+).(\d+).(\d+)", "$1-$2-$3 $4:$5:$6.$7");
It just cuts all the numerics apart from the gibberish around it and constructs the date you want to.
Upvotes: 2
Reputation: 148110
You can parse it using DateTime.ParseExact by Custom Date and Time Format Strings
DateTime dt = DateTime.ParseExact( "2014-01-07-15.26.46.000452",
"yyyy-MM-dd-H.m.s.ffffff",
System.Globalization.CultureInfo.InvariantCulture);
Upvotes: 5