DateTime Conversion Regex C#
I've inherited a codebase littered with DateTime objects cre开发者_JS百科ated 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?
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.
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));
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)
精彩评论