views:

62

answers:

3

I've inherited a codebase littered with DateTime objects created like this:

DateTime d = Convert.ToDateTime("2008-02-05");

which are failing when tests are ran on NY servers due to the culture of the string. I wish to convert them to the more sensible format:

DateTime d = new DateTime(2008,02,05);

I've written a VS macro that converts them one at a time, but I wondered if someone could help me write a regex so that I can find and replace them in bulk?

+2  A: 

Assuming they're all in the same format (i.e. no additional spaces somewhere in between brackets and/or other locations), then search for:

Convert\.ToDateTime\("(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})"\);

and replace with:

 new DateTime(${year}, ${month}, ${day});

Note that this does not take in the context of the statement in anyway. It's fire and forget, replacing any and every occurence everywhere, in any context.

Willem van Rumpt
@robyaw: Why bother?
Alan Moore
A: 

After some research into the arcane VS Find /Replace regex commands it wasn't too hard and Willem's answer went a long way to help. I got:

//find
Convert\.ToDateTime\(\"{[0-9]^4}-{[0-9]+}-{[0-9]+}\"\)

//replace
new DateTime(\1, \2, \3)
burnside
Just for the record (since the occurence of the pattern is not very likely): Be aware that the "Convert.ToDateTime" part of this regex will actually match "Convert[ANY CHARACTER]ToDateTime". Change it to "Convert\.ToDateTime" to avoid it, if necessary.
Willem van Rumpt
A: 

Did You try using substrings instead of regex

string dateString = "2008-07-26"
string.Format("{0}-{1}-{2}",dateString.Substring(0,4),dateString.Substring(5,2),dateString.Substring(8,2));
adopilot